//电子邮件puhalskijsemen@gmail.com
//源码网站 开vpn全局模式打开 http://web3incubators.com/
//电报https://t.me/gamecode999
//网页客服 http://web3incubators.com/kefu.html

import { ADMgr } from "./ADManager";
import AICtrl from "./AIControl";
import { AudioMgr } from "./AudioManager";
import { BuffMgr } from "./BuffMag";
import { BundleNames } from "./BundleConfig";
import { EVENT_TYPE } from "./EvenType";
import { EventMgrInstance } from "./EventManager";
import { Excel } from "./Excel";
import { GameDataMgr } from "./GameDataManager";
import { GameGlobalVariable } from "./GameGlobalVariable";
import { GuideCtrlInstance } from "./GuideControl";
import ItemCellFatherMove from "./Item_CellFatherMove";
import ItemGameBagCell from "./Item_GameBagCell";
import ItemGameEquip from "./Item_GameEquip";
import ItemPaiZi from "./Item_PaiZi";
import { LogMgr } from "./LogManager";
import LogicGetEquip from "./Logic_GetEquip";
import { PlayerDataMgr } from "./PlayerDataManager";
import UIManager from "./UIManager";
import UIViewBase from "./UIView";
import UIBagUIBindings from "./UI_Bag_UIBindings";
import { TipMgr } from './TipsManager';
import { GuideName, GameBagGuideIndex } from "./Const_Common";
import { VideoPurchaseData, FruitId } from "./Const_Game";
import { UIView_Game } from "./UIConfig_Game";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ViewGameBag extends UIViewBase {
    @property(UIBagUIBindings)
    public auto_ui: UIBagUIBindings = null;

    @property(cc.Prefab)
    private paiZiPfb: cc.Prefab = null;

    public maxX: number = 5;
    public maxY: number = 7;
    public startX: number = 3;
    public startY: number = 3;
    public effectMax: number = 60;
    public oneBuyMoney: number = 15;
    public videoGetMoney: number = 30;
    public xifuTime: number = 0.15;
    public moveTime: number = 0.22;
    public viewNodePosY: number = 100;

    public lastPickArray: ItemGameBagCell[] = [];
    public cellCompMap: Map<number, ItemGameBagCell> = new Map();
    public equipPool: Map<string, ItemGameEquip> = new Map();
    public dressUpEquipMap: Map<string, ItemGameEquip> = new Map();
    public baseCellCompArray: ItemGameBagCell[] = [];
    public currAddCellDataMap: Map<string, { cellNode: cc.Node; pickCellArray: ItemGameBagCell[] }> = new Map();
    public selfMap: { [key: string]: any } = {};
    public firstUseArray: number[] = [];
    public childPosMap: Map<string, cc.Vec2> = new Map();

    public currPickNode: cc.Node = null;
    public currPickNodeComp: ItemGameEquip = null;
    public moveLength: number = 0;
    public guide4Time: number = -1;
    public isUpBuffCdTime: boolean = false;
    public upBuffArray: cc.Node[] = [];
    public jianTouArray: cc.Node[] = [];
    public mustResetTime: number = -1;

    public cellFatherMove: ItemCellFatherMove;
    public guideShou: cc.Node;
    public guideSGComp: ItemGameEquip;
    public aiPickEquip: ItemGameEquip;
    public aiPickCell: ItemGameBagCell[];
    public aiPickOtherEquip: ItemGameEquip;

    protected _show(...args: any[]): void {
        LogicGetEquip.getInstance.resetThis();
    }

    private gameOpenMoveTween(isOpen: boolean, callback?: () => void): void {
        const targetY = isOpen ? this.viewNodePosY : 0;
        this.auto_ui.node_viewNode.y = targetY;
        if (callback) {
            callback();
        }
    }

    start(): void {
        this.scheduleOnce(() => {
            LogMgr.debug(this.node.height);
            this.auto_ui.node_DragFather.y =
                cc.winSize.height / cc.winSize.width > 2 ? -540 : -500;
        });
    }

    protected _addEventListener(): void {
        this._addEvent(EVENT_TYPE.ResetGameBagAI, this.checkAI, this);
    }

    public openView(options?: { isGameEnd: boolean }): void {
        this.auto_ui.btn_VideoResetBtn.node.active = true;
        this.gameOpenMoveTween(true, () => {
            this.scheduleOnce(() => {
                this.checkBottomBtnScale();
            }, 0.15);

            if (options && options.isGameEnd) {
                if (
                    PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) ===
                    GameBagGuideIndex.EntryGuide7Completion
                ) {
                    PlayerDataMgr.setGuideIndex(
                        GuideName.GameBag,
                        GameBagGuideIndex.GridGuide8
                    );
                } else {
                    this.scheduleOnce(() => {
                        this.checkAI();
                    }, AICtrl._instance.fightDelayTime);
                }

                if (BuffMgr.getSecondaryFruitBuff()) {
                    LogMgr.debug("有二级必得buff，必出二级水果");
                    this.resetEquip(true, true, true);
                } else {
                    this.resetEquip(true, false, true);
                }

                this.checkGuide();

                this.scheduleOnce(() => {
                    this.dressUpEquipMap.forEach((equip) => {
                        if (equip.equipData.shuiguoId === 1002) {
                            const buff = BuffMgr.getFruitBuff(
                                1002,
                                equip.equipData.equipLevel
                            );
                            EventMgrInstance.emitEvent(
                                EVENT_TYPE.Game_Add_YinBi,
                                buff.nowvalue,
                                equip.node.convertToWorldSpaceAR(cc.v2(0, 0))
                            );
                        }
                    });
                }, 0.5);
            }
        });
    }

    onEnable(): void {
        this.changeSliderLabelColor();
    }

    private changeSliderLabelColor(): void {
        const sliderCoin = GameDataMgr.getSilverCoin;
        this.auto_ui.node_sliverLabelNode.color =
            sliderCoin >= this.oneBuyMoney ? cc.Color.WHITE : cc.Color.RED;
    }

    onLoad(): void {
        this.init("", "", null);

        this.auto_ui.dbAnim_heChengEffect.addEventListener(
            dragonBones.EventObject.COMPLETE,
            () => {
                this.auto_ui.dbAnim_heChengEffect.node.active = false;
            },
            this
        );

        this._loadRes(
            BundleNames.Game,
            `res/bg/gezibg${GameGlobalVariable.getSceneId()}`,
            cc.SpriteFrame
        ).then((spriteFrame) => {
            this.auto_ui.node_diTuNode.getComponent(cc.Sprite).spriteFrame =
                spriteFrame;
        });

        this.auto_ui.btn_VideoGetCell.node.active = false;

        if (
            PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) ===
            GameBagGuideIndex.GuideCompletion
        ) {
            this.auto_ui.btn_VideoGetCell.node.active =
                this.maxX * this.maxY - this.cellCompMap.size > 0 &&
                GameDataMgr.getGameBag.videoCellCount <
                GameGlobalVariable.bagVideoCellCount;
        }

        this.gameOpenMoveTween(true, () => {
            this.startSet();
            this.scheduleOnce(() => {
                this.checkBottomBtnScale();
            }, 0.15);
        });
    }

    private startSet(): void {
        this.auto_ui.btn_UseGeZiBtn.node.active = false;
        this.auto_ui.node_useGeZiTip.active = false;

        this.cellFatherMove =
            this.auto_ui.node_DragEndNode.getComponent(ItemCellFatherMove);
        this.cellFatherMove.initializeSettings(this);

        for (let i = this.auto_ui.node_DragFather.childrenCount - 1; i >= 0; i--) {
            this.recycleEquip(this.auto_ui.node_DragFather.children[i]);
        }

        let needInit = false;
        if (!GameDataMgr.getGameBag.bagArray) {
            GameDataMgr.getGameBag.bagArray = [];
            needInit = true;

            const offsetX = (this.maxX - this.startX) / 2;
            const offsetY = (this.maxY - this.startY) / 2;
            const startX = Math.floor(offsetX);
            const endX = Math.ceil(offsetX);
            const startY = Math.floor(offsetY);
            const endY = Math.ceil(offsetY);

            for (let y = 0; y < this.maxY; y++) {
                for (let x = 0; x < this.maxX; x++) {
                    let value = 0;
                    if (
                        x < startX ||
                        x >= this.maxX - endX ||
                        y < startY ||
                        y >= this.maxY - endY
                    ) {
                        value = -1;
                    }
                    GameDataMgr.getGameBag.bagArray.push(value);
                }
            }
        }

        const cubeFather = this.auto_ui.node_cubeFather;
        if (cubeFather.childrenCount === 0) {
            this.auto_ui.node_diTuNode.active = true;
            const cubeBaseFather = this.auto_ui.node_cubeBaseFather;

            for (let i = 0; i < this.maxX * this.maxY; i++) {
                let cubeItem: cc.Node;
                if (i < cubeBaseFather.childrenCount) {
                    cubeItem = cubeBaseFather.children[i];
                } else {
                    cubeItem = cc.instantiate(this.auto_ui.node_cubeItem);
                    cubeItem.parent = cubeBaseFather;
                }

                cubeItem.active = true;
                const cellComp = cubeItem.getComponent(ItemGameBagCell);
                cellComp.initializeSettings({ cellIndex: i }, false);
                cellComp.temporaryShowBgNode(true);
                this.baseCellCompArray.push(cellComp);
            }

            cubeBaseFather.opacity = 0;
            this.cellCompMap.clear();

            for (let y = 0; y < this.maxY; y++) {
                for (let x = 0; x < this.maxX; x++) {
                    const index = y * this.maxX + x;
                    const value = GameDataMgr.getGameBag.bagArray[index];

                    if (value !== -1) {
                        const cubeItem = cc.instantiate(this.auto_ui.node_cubeItem);
                        const cellComp = cubeItem.getComponent(ItemGameBagCell);
                        this.cellCompMap.set(index, cellComp);

                        cubeItem.name = `方块${index}`;
                        cubeItem.parent = cubeFather;
                        cubeItem.active = true;

                        cellComp.initializeSettings({ cellIndex: index }, value !== -1);
                    }
                }
            }

            this.scheduleOnce(() => {
                this.cellCompMap.forEach((cellComp) => {
                    cellComp.node.setPosition(
                        cubeFather.convertToNodeSpaceAR(
                            cubeBaseFather.children[cellComp.cellData.cellIndex].convertToWorldSpaceAR(
                                cc.v2(0, 0)
                            )
                        )
                    );
                });

                const spacing = cc.v2(44, 32);
                this.changeSizeByChild(this.auto_ui.node_cubeFather, spacing);
                this.setBgNodeSize(false);
            });
        }

        this.startShowEquip(needInit);

        if (
            !GameDataMgr.getGameBag.cellWposArray ||
            GameDataMgr.getGameBag.cellWposArray.length === 0
        ) {
            this.SaveCellWpos();
        }

        if (
            PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) ===
            GameBagGuideIndex.EntryGuide7Completion
        ) {
            PlayerDataMgr.gmSetGuideIndex(
                GuideName.GameBag,
                GameBagGuideIndex.StartBattleGuide6
            );
        }

        if (
            PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) !==
            GameBagGuideIndex.GuideCompletion
        ) {
            this.checkGuide();
        } else {
            this.scheduleOnce(() => {
                this.checkAI();
            });
        }
    }

    private startShowEquip(needInit: boolean): void {
        this.dressUpEquipMap.clear();
        this.equipPool.clear();

        const gameBag = GameDataMgr.getGameBag;

        if (gameBag.dressUpEquips) {
            const wPositions: cc.Vec2[] = [];
            const equipNodes: cc.Node[] = [];

            gameBag.dressUpEquips.forEach((equipData) => {
                const equipNode = this.getEquipNode(equipData.pfbName);
                equipNode.parent = this.auto_ui.node_DragEndNode;
                equipNode.active = true;

                wPositions.push(equipData.wPostion);
                equipNodes.push(equipNode);

                const equipComp = equipNode.getComponent(ItemGameEquip);
                const isLocked = equipData.equipLevel === -1;
                equipComp.initializeSettings(
                    equipData,
                    isLocked,
                    this.onChildTouchStart.bind(this),
                    this.onChildTouchMove.bind(this),
                    this.onChildTouchUp.bind(this),
                    this.makePaiZi.bind(this)
                );

                this.dressUpEquipMap.set(equipNode.uuid, equipComp);

                const lockCells: ItemGameBagCell[] = [];
                equipData.lockCellIndex.forEach((cellIndex) => {
                    this.cellCompMap.get(cellIndex).dragEndLockThis(equipComp);
                    lockCells.push(this.cellCompMap.get(cellIndex));
                });
                equipComp.dragEndLockCell(lockCells);
            });

            this.scheduleOnce(() => {
                wPositions.forEach((wPos, index) => {
                    const localPos = equipNodes[
                        index
                    ].parent.convertToNodeSpaceAR(wPos);
                    equipNodes[index].setPosition(
                        cc.v2(localPos.x, localPos.y + this.viewNodePosY)
                    );
                });
            });
        }

        if (gameBag.equipPool && gameBag.equipPool.length > 0) {
            gameBag.equipPool.forEach((equipData) => {
                const equipNode = this.getEquipNode(equipData.pfbName);
                equipNode.parent = this.auto_ui.node_DragFather;
                equipNode.active = true;
                equipNode.setPosition(0, 0);

                const equipComp = equipNode.getComponent(ItemGameEquip);
                const isLocked = equipData.equipLevel === -1;
                equipComp.initializeSettings(
                    equipData,
                    isLocked,
                    this.onChildTouchStart.bind(this),
                    this.onChildTouchMove.bind(this),
                    this.onChildTouchUp.bind(this),
                    this.makePaiZi.bind(this)
                );

                this.equipPool.set(equipComp.node.uuid, equipComp);
            });
        } else if (needInit) {
            this.resetEquip(true, false, true);
        }

        this.checkDragFatherLayout();
    }

    private sliderResetClick(): void {
        if (GameDataMgr.getSilverCoin >= this.oneBuyMoney) {
            this.resetEquip(false, false, false);
        } else {
            const videoBuyOneData = new VideoPurchaseData();
            videoBuyOneData.titleStr = "银币不足";
            videoBuyOneData.coinCount = this.videoGetMoney;
            videoBuyOneData.infoStr = `是否观看视频，获得${this.videoGetMoney}银币`;
            videoBuyOneData.clickCallBack = () => {
                GameDataMgr.addSilverCoin(this.videoGetMoney);
                this.changeSliderLabelColor();
                EventMgrInstance.emitEvent(
                    EVENT_TYPE.Game_Add_YinBi,
                    this.videoGetMoney,
                    this.node.convertToWorldSpaceAR(cc.v2(0, 0)),
                    null,
                    false
                );
            };
            UIManager.open(
                BundleNames.Game,
                UIView_Game.UI_VideoBuyOne,
                videoBuyOneData
            );
        }
    }

    /**
     * 点击监听器
     * @param target 目标节点
     */
    protected _clickListener(target: cc.Button): void {
        const ui = this.auto_ui;
        switch (target) {
            case ui.btn_ResetBtn:
                this.sliderResetClick();
                break;
            case ui.btn_VideoResetBtn:
                let adName = "背包视频刷新";
                if (GameGlobalVariable.isSpecialLevel() === 1) {
                    adName = "无尽模式背包视频刷新";
                } else {
                    const boshu = GameDataMgr.getCurrentLevelWaveState(
                        GameGlobalVariable.nowlevel,
                        2
                    );
                    adName = `${GameGlobalVariable.nowlevel}章_${boshu + 1}波_${adName}`;
                }
                ADMgr.showRewardedVideoAd(adName, () => {
                    this.resetEquip(false, true, false);
                    ui.btn_VideoResetBtn.node.active = false;
                    this.checkBottomBtnScale();
                });
                break;
            case ui.btn_start:
                this.gameStart();
                break;
            case ui.btn_UseGeZiBtn:
                this.setCellFatherMove(false);
                break;
            case ui.btn_VideoGetCell:
                this.videoGetCell();
                break;
        }
    }

    /**
     * 视频获取格子
     */
    private videoGetCell(): void {
        let adName = "背包视频获取扩展格子";
        if (GameGlobalVariable.isSpecialLevel() === 1) {
            adName = "无尽模式背包视频获取扩展格子";
        } else {
            const boshu = GameDataMgr.getCurrentLevelWaveState(
                GameGlobalVariable.nowlevel,
                2
            );
            adName = `${GameGlobalVariable.nowlevel}章_${boshu + 1}波_${adName}`;
        }
        ADMgr.showRewardedVideoAd(adName, () => {
            const maxVideoCellCount = GameGlobalVariable.bagVideoCellCount;
            GameDataMgr.getGameBag.videoCellCount++;
            const remainCount = `${maxVideoCellCount - GameDataMgr.getGameBag.videoCellCount}`;
            this.auto_ui.node_videoLastCount.children.forEach((child) => {
                child.active = child.name === remainCount;
            });
            this.auto_ui.btn_VideoGetCell.node.active =
                this.maxX * this.maxY - this.cellCompMap.size > 0 &&
                GameDataMgr.getGameBag.videoCellCount < maxVideoCellCount;
            console.log(
                this.maxX * this.maxY - this.cellCompMap.size,
                GameDataMgr.getGameBag.videoCellCount,
                maxVideoCellCount
            );
            GameDataMgr.saveGameBagData();
            this.checkBottomBtnScale();

            const newCells = LogicGetEquip.getInstance.getOneCell(
                1,
                this.maxX * this.maxY - this.cellCompMap.size,
                GameDataMgr.getGameBag.videoCellCount
            );
            for (let i = 0; i < newCells.length; i++) {
                const cellData = newCells[i];
                if (cellData) {
                    const equipNode = this.getEquipNode(cellData.pfbName);
                    if (!equipNode) continue;

                    equipNode.parent = this.auto_ui.node_DragFather;
                    if (this.auto_ui.node_DragFather.childrenCount > 1) {
                        equipNode.setSiblingIndex(Math.floor(this.auto_ui.node_DragFather.childrenCount / 2));
                    }
                    equipNode.active = true;

                    const equipComp = equipNode.getComponent(ItemGameEquip);
                    const isLocked = cellData.level === -1;
                    const equipLevel = isLocked ? cellData.level : cellData.level - 1;
                    const equipData = {
                        shuiguoId: cellData.shuiguoId,
                        equipLevel: equipLevel,
                        lockCellIndex: [],
                        pfbName: cellData.pfbName,
                        isHaveQiPao: cellData.isHaveQiPao === 1
                    };
                    equipComp.initializeSettings(
                        equipData,
                        isLocked,
                        this.onChildTouchStart.bind(this),
                        this.onChildTouchMove.bind(this),
                        this.onChildTouchUp.bind(this),
                        this.makePaiZi.bind(this)
                    );
                    this.addEquipPoolData(equipComp);
                }
            }
            AudioMgr.playSoundEffect("sound/resetEquip", false, BundleNames.Game);
        });
    }

    private gameStart(): void {
        if (this.dressUpEquipMap.size > 0) {
            EventMgrInstance.emitEvent(EVENT_TYPE.Game_OpenGame);
            GameDataMgr.getGameBag.equipPool.length = 0;
            for (let i = this.auto_ui.node_DragFather.childrenCount - 1; i >= 0; i--) {
                this.recycleEquip(this.auto_ui.node_DragFather.children[i]);
            }
            this.gameOpenMoveTween(false, null);
        } else {
            TipMgr.showToast("请先上阵水果");
        }
    }

    private resetEquip(
        isInit: boolean,
        isVideo: boolean,
        isGameEnd: boolean
    ): void {
        if (!isInit && !isVideo) {
            if (!GameDataMgr.subtractSilverCoin(this.oneBuyMoney)) {
                return;
            }
            this.changeSliderLabelColor();
        }

        this.makeEquip(isVideo ? 4 : 3, isVideo, isGameEnd);
        this.saveData();
        this.checkDragFatherLayout();
    }

    private makeEquip(count: number, isVideo: boolean, isGameEnd: boolean): void {
        AudioMgr.playSoundEffect("sound/resetEquip", false, BundleNames.Game);

        let boshu = GameDataMgr.getCurrentLevelWaveState(
            GameGlobalVariable.nowlevel,
            2
        ) + 1;
        if (GameGlobalVariable.isSpecialLevel() === 1 || !isGameEnd) {
            boshu = 2;
        }

        let equips = LogicGetEquip.getInstance.getEquip(
            count,
            isVideo,
            this.maxX * this.maxY - this.cellCompMap.size,
            boshu
        );

        if (boshu === 1 && isGameEnd) {

            let level1Equip: any;
            for (let i = 0; i < equips.length; i++) {
                const equip = equips[i];
                if (
                    equip.level === 1 &&
                    equip.shuiguoId !== FruitId.杨桃忍者 &&
                    equip.shuiguoId !== FruitId.柠檬精 &&
                    equip.shuiguoId !== FruitId.辣妹子 &&
                    equip.shuiguoId !== FruitId.招财橙子
                ) {
                    level1Equip = equip;
                    break;
                }
            }
            if (level1Equip) {
                for (let i = 0; i < equips.length; i++) {
                    const equip = equips[i];
                    if (equip.level === 1 && equip.shuiguoId !== level1Equip.shuiguoId) {
                        equips[i] = level1Equip;
                        break;
                    }
                }
            }

        }

        if (
            PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) ===
            GameBagGuideIndex.InitialGuide1
        ) {
            equips = [Excel.bagEquipRule(14), Excel.bagEquipRule(32), Excel.bagEquipRule(12)];
        } else if (
            PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) ===
            GameBagGuideIndex.RefreshButtonGuide3
        ) {
            equips = [Excel.bagEquipRule(14), Excel.bagEquipRule(32), Excel.bagEquipRule(10)];
        } else if (
            PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) ===
            GameBagGuideIndex.GridGuide8
        ) {
            equips = [Excel.bagEquipRule(2), Excel.bagEquipRule(30), Excel.bagEquipRule(10)];
        }

        if (isGameEnd && this.maxX * this.maxY - this.cellCompMap.size > 0) {
            const mustGetGeZi = LogicGetEquip.getInstance.getMustGetGeZi();
            if (mustGetGeZi) {
                equips[Math.floor(Math.random() * equips.length)] = mustGetGeZi;
            }
        }

        for (let i = this.auto_ui.node_DragFather.childrenCount - 1; i >= 0; i--) {
            this.recycleEquip(this.auto_ui.node_DragFather.children[i]);
        }

        this.equipPool.clear();
        GameDataMgr.getGameBag.equipPool = [];

        for (let i = 0; i < count; i++) {
            const equipData = equips[i];
            const equipNode = this.getEquipNode(equipData.pfbName);
            if (equipNode) {
                equipNode.parent = this.auto_ui.node_DragFather;
                equipNode.active = true;

                const equipComp = equipNode.getComponent(ItemGameEquip);
                const isLocked = equipData.level === -1;
                const equipLevel = isLocked ? equipData.level : equipData.level - 1;
                const newEquipData = {
                    shuiguoId: equipData.shuiguoId,
                    equipLevel: equipLevel,
                    lockCellIndex: [],
                    pfbName: equipData.pfbName,
                    isHaveQiPao: equipData.isHaveQiPao === 1
                };
                equipComp.initializeSettings(
                    newEquipData,
                    isLocked,
                    this.onChildTouchStart.bind(this),
                    this.onChildTouchMove.bind(this),
                    this.onChildTouchUp.bind(this),
                    this.makePaiZi.bind(this)
                );
                this.addEquipPoolData(equipComp);
            }
        }

        this.childPosMap.clear();
    }

    private onChildTouchStart(event: cc.Event.EventTouch): void {
        if (!this.currPickNode) {
            const targetNode = event.target.parent.parent;
            this.setTouchStartNode(targetNode);
        }
    }

    private setTouchStartNode(node: cc.Node): void {
        this.childPosMap.set(node.uuid, node.getPosition());
        this.currPickNode = node;
        this.currPickNodeComp = node.getComponent(ItemGameEquip);

        const worldPos = this.currPickNode.convertToWorldSpaceAR(cc.v2(0, 0));
        this.currPickNode.parent = this.auto_ui.node_DragTempNode;
        this.currPickNode.setPosition(this.auto_ui.node_DragTempNode.convertToNodeSpaceAR(worldPos));

        if (this.currPickNodeComp.isGeZiType) {
            this.setCellFatherMove(true);
        }

        this.currPickNode.angle = 0;
        this.moveLength = 0;

        if (
            !(
                (-1 == this.guide4Time &&
                    PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) !=
                    GameBagGuideIndex.GridGuide8) ||
                !this.guideShou
            )
        ) {
            this.guideShou.active = !1;
        }

        if (!(this.currPickNodeComp.lockCellArray && this.currPickNodeComp.lockCellArray.length !== 0)) {
            this.checkDragFatherLayout(this.currPickNode.uuid, -1);
        }

        AudioMgr.playSoundEffect("effect/dianEquip");

        if (
            this.currPickNodeComp &&
            this.currPickNodeComp.equipData.equipLevel === GameGlobalVariable.normalMaxLevel - 1
        ) {
            EventMgrInstance.emitEvent(EVENT_TYPE.Game_Show_Level5Tip, {
                isShow: true,
                shuiGuoId: this.currPickNodeComp.equipData.shuiguoId
            });
        }

        this.currPickNodeComp.displayUnlockLevel5Tip(true, this.equipPool, this.dressUpEquipMap);
    }

    private onChildTouchMove(event: cc.Event.EventTouch): void {
        if (this.currPickNode) {
            const touchPos = this.currPickNode.parent.convertToNodeSpaceAR(event.getLocation());
            this.currPickNode.setPosition(touchPos);

            if (Math.abs(event.getDeltaX()) + Math.abs(event.getDeltaY()) > 3) {
                const checkResult = this.checkCellIsOk(false);
                this.moveLength += Math.abs(event.getDeltaX()) + Math.abs(event.getDeltaY());

                if (this.currPickNodeComp.equipData.shuiguoId === FruitId.柠檬精) {
                    if (checkResult.pickCellArray) {
                        const cellIndexes: number[] = [];
                        checkResult.pickCellArray.forEach((cell) => {
                            cellIndexes.push(cell.cellData.cellIndex);
                        });
                        this.checkUpBuff(cellIndexes, false);
                    } else {
                        this.hideJianTou();
                    }
                }
            }
        }
    }

    private onChildTouchUp(): void {


        if (this.currPickNode) {
            this.currPickNodeComp.displayUnlockLevel5Tip(false, null, null);
            EventMgrInstance.emitEvent(EVENT_TYPE.Game_Show_Level5Tip, {
                isShow: false,
                shuiGuoId: 0
            });

            this.hideJianTou();

            if (
                this.moveLength < 10 &&
                !this.currPickNodeComp.isGeZiType &&
                !this.currPickNodeComp.qiPaoNode.active
            ) {
                UIManager.open(BundleNames.Game, UIView_Game.UI_GameEquipInfo, {
                    shuiGuoId: this.currPickNodeComp.equipData.shuiguoId,
                    level: this.currPickNodeComp.equipData.equipLevel
                });
            }

            this.moveLength = 0;
            this.currPickNode.angle = 0;

            const equipComp = this.currPickNodeComp;
            equipComp.displayPurchaseView(
                () => {
                    if (this.lastPickArray.length > 0) {
                        this.lastPickArray.forEach((cell) => {
                            cell.updateBgNodeColor(cc.Color.WHITE);
                        });
                    }

                    if (equipComp.lockCellArray) {
                        equipComp.lockCellArray.forEach((cell) => {
                            cell.dragEndLockThis(null);
                        });
                        equipComp.dragEndLockCell(null);
                        this.removeDressUplData(equipComp.node.uuid);
                        this.addEquipPoolData(equipComp);
                    }

                    this.currAddCellDataMap.delete(equipComp.node.uuid);
                    this.backToDady(equipComp);
                    this.currPickNode = null;
                },
                () => {
                    this.touchUpEndCall();
                }
            );
        }
    }

    private touchUpEndCall(): void {
        const checkResult = this.checkCellIsOk(true);
        if (this.lastPickArray.length > 0) {
            this.lastPickArray.forEach((cell) => {
                cell.updateBgNodeColor(cc.Color.WHITE);
            });
        }
        this.lastPickArray.length = 0;
        let equipComp = this.currPickNodeComp;

        if (
            PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) ===
            GameBagGuideIndex.SynthesisGuide4
        ) {
            if (this.guide4Time === 2) {
                if (checkResult.otherEquip) {
                    checkResult.isOk = false;
                }
            } else if (
                this.guide4Time === -1 ||
                this.currPickNodeComp.equipData.equipLevel !== 0 ||
                !(
                    checkResult.otherEquip &&
                    checkResult.otherEquip.equipData.shuiguoId === this.currPickNodeComp.equipData.shuiguoId
                )
            ) {
                checkResult.isOk = false;
            }
        }

        if (!checkResult.isOk || (checkResult.otherEquip && checkResult.otherEquip.equipData.isHaveQiPao)) {
            this.handleCheckIsNotOk(equipComp);
        } else {
            this.handleCheckIsOk(equipComp, checkResult);
        }

        this.currPickNode = null;
        this.saveData();
        this.scheduleOnce(() => {
            this.checkAI();
        }, AICtrl._instance.startDelayTime);
    }

    private handleCheckIsNotOk(equipComp: ItemGameEquip): void {
        if (this.currPickNodeComp.isGeZiType) {
            this.currAddCellDataMap.delete(this.currPickNodeComp.node.uuid);
        }

        if (this.currPickNodeComp.lockCellArray) {
            this.currPickNodeComp.lockCellArray.forEach((cell) => {
                cell.dragEndLockThis(null);
            });
            this.currPickNodeComp.dragEndLockCell(null);
            this.removeDressUplData(this.currPickNode.uuid);
            this.addEquipPoolData(this.currPickNodeComp);
        }

        if (this.guide4Time !== -1 && this.guideShou) {
            this.guideShou.active = true;
            this.currPickNode.setSiblingIndex(0);
        }

        this.backToDady(this.currPickNodeComp);
    }

    private handleCheckIsOk(equipComp: ItemGameEquip, checkResult: any): void {
        AudioMgr.playSoundEffect("effect/fangEquip");

        if (
            this.guideShou &&
            PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) !==
            GameBagGuideIndex.GridGuide8
        ) {
            GuideCtrlInstance.recycleOneFingerGuide(this.guideShou);
            this.guideShou = null;
            this.scheduleOnce(() => {
                this.checkGuide();
            }, 0.5);
        }

        if (
            PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) ===
            GameBagGuideIndex.GridGuide8 &&
            this.currPickNodeComp.isGeZiType &&
            this.guideCheckCell(checkResult.pickCellArray)
        ) {
            this.showGuide8_1();
        }

        if (checkResult.pickCellArray) {
            this.handlePickCell(checkResult, equipComp);
        } else if (checkResult.otherEquip) {
            this.handleOtherEquip(checkResult, equipComp);
        }

        if (this.currPickNodeComp.equipData.shuiguoId === FruitId.柠檬精) {
            this.checkUpBuff(this.currPickNodeComp.equipData.lockCellIndex, true);
        }
    }

    private handlePickCell(checkResult: any, equipComp: ItemGameEquip): void {
        if (this.currPickNodeComp.isGeZiType) {
            this.currAddCellDataMap.set(this.currPickNode.uuid, {
                cellNode: this.currPickNode,
                pickCellArray: checkResult.pickCellArray
            });
            this.currPickNode.runAction(
                cc.moveTo(
                    this.xifuTime,
                    this.currPickNode.x + checkResult.effectPos.x,
                    this.currPickNode.y + checkResult.effectPos.y
                )
            );
        } else {
            if (this.currPickNodeComp.lockCellArray) {
                this.currPickNodeComp.lockCellArray.forEach((cell) => {
                    GameDataMgr.getGameBag.bagArray[cell.cellData.cellIndex] = 0;
                    cell.dragEndLockThis(null);
                });
                this.removeDressUplData(this.currPickNode.uuid);
            } else {
                this.removeEquipPoolData(this.currPickNode.uuid);
            }

            checkResult.pickCellArray.forEach((cell) => {
                if (cell.equipComp && this.dressUpEquipMap.has(cell.equipComp.node.uuid)) {
                    this.removeDressUplData(cell.equipComp.node.uuid);
                    const equipComp = cell.equipComp;
                    equipComp.lockCellArray.forEach((lockCell) => {
                        GameDataMgr.getGameBag.bagArray[lockCell.cellData.cellIndex] = 0;
                        lockCell.dragEndLockThis(null);
                    });
                    equipComp.dragEndLockCell(null);
                    this.addEquipPoolData(equipComp);
                    this.backToDady(equipComp);
                }
            });

            this.currPickNode.parent = this.auto_ui.node_DragEndNode;
            const targetPos = cc.v2(
                this.currPickNode.x + checkResult.effectPos.x,
                this.currPickNode.y + checkResult.effectPos.y
            );
            this.currPickNode.runAction(
                cc.sequence(
                    cc.moveTo(this.xifuTime, targetPos.x, targetPos.y),
                    cc.delayTime(0.15),
                    cc.callFunc(() => {
                        this.checkDressUpLabel(equipComp);
                    })
                )
            );

            this.currPickNodeComp.dragEndLockCell(checkResult.pickCellArray);
            checkResult.pickCellArray.forEach((cell) => {
                GameDataMgr.getGameBag.bagArray[cell.cellData.cellIndex] = 1;
                cell.dragEndLockThis(this.currPickNodeComp);
            });

            this.addDressUpData(this.currPickNodeComp, targetPos);
        }
    }

    private handleOtherEquip(checkResult: any, equipComp: ItemGameEquip): void {
        const otherLockCells = checkResult.otherEquip.lockCellArray;
        const currLockCells = this.currPickNodeComp.lockCellArray;
        let isZaZhong = false;
        let zaZhongWorldPos = null;

        if (
            this.currPickNodeComp.equipData.equipLevel <
            GameGlobalVariable.normalMaxLevel - 1
        ) {
            this.currPickNodeComp.equipData.equipLevel++;
            // mg.vibrateShort();
        } else if (
            this.currPickNodeComp.equipData.equipLevel <
            GameGlobalVariable.zaZhongMaxLevel - 1
        ) {
            isZaZhong = true;
            const shuiguoData = Excel.shuiguo(this.currPickNodeComp.equipData.shuiguoId);
            const otherEquip = checkResult.otherEquip;
            const currEquip = this.currPickNodeComp;

            if (shuiguoData.jinjieShuiGuoId === 0) {
                zaZhongWorldPos = otherEquip.node.convertToWorldSpaceAR(cc.v2(0, 0));
                const currWorldPos = this.currPickNodeComp.node.convertToWorldSpaceAR(cc.v2(0, 0));
                checkResult.otherEquip = currEquip;
                checkResult.otherEquip.node.setPosition(
                    checkResult.otherEquip.node.parent.convertToNodeSpaceAR(currWorldPos)
                );
                this.currPickNodeComp = otherEquip;
                this.currPickNodeComp.node.setPosition(
                    this.currPickNodeComp.node.parent.convertToNodeSpaceAR(
                        zaZhongWorldPos
                    )
                );
                equipComp = this.currPickNodeComp;
                checkResult.zaZhongPickCells = otherLockCells;
            }

            this.removeDressUplData(otherEquip.node.uuid);
            this.removeDressUplData(currEquip.node.uuid);
            this.removeEquipPoolData(otherEquip.node.uuid);
            this.removeEquipPoolData(currEquip.node.uuid);

            this.currPickNodeComp.equipData.equipLevel++;
            // mg.vibrateShort();

            UIManager.open(BundleNames.Game, UIView_Game.UI_GetZaZhong, {
                shuiGuoId: this.currPickNodeComp.equipData.shuiguoId,
            });
        }

        if (isZaZhong) {
            AudioMgr.playSoundEffect("sound/upLevel5", false, BundleNames.Game);
        } else {
            AudioMgr.playSoundEffect("effect/gameBagHeCheng");
        }

        this.currPickNodeComp.resetShow();
        this.showDragBone(checkResult.otherEquip.node.convertToWorldSpaceAR(cc.v2(0, 0)));
        this.currPickNode.angle = 0;

        if (
            otherLockCells &&
            checkResult.otherEquip.equipData.pfbName === this.currPickNodeComp.equipData.pfbName
        ) {
            if (currLockCells) {
                currLockCells.forEach((cell) => {
                    GameDataMgr.getGameBag.bagArray[cell.cellData.cellIndex] = 0;
                    cell.dragEndLockThis(null);
                });
                this.removeDressUplData(this.currPickNode.uuid);
            } else {
                this.removeEquipPoolData(this.currPickNode.uuid);
            }

            this.currPickNodeComp.dragEndLockCell(otherLockCells);
            this.currPickNodeComp.lockCellArray.forEach((cell) => {
                cell.dragEndLockThis(this.currPickNodeComp);
            });

            this.currPickNode.parent = this.auto_ui.node_DragEndNode;
            const targetPos = checkResult.otherEquip.node.getPosition();
            this.currPickNode.runAction(
                cc.sequence(
                    cc.moveTo(this.xifuTime, targetPos.x, targetPos.y),
                    cc.delayTime(0.15),
                    cc.callFunc(() => {
                        this.checkUpLevelLabel(equipComp);
                    })
                )
            );

            this.removeDressUplData(checkResult.otherEquip.node.uuid);
            this.addDressUpData(this.currPickNodeComp, targetPos);
        } else {
            if (otherLockCells) {
                otherLockCells.forEach((cell) => {
                    GameDataMgr.getGameBag.bagArray[cell.cellData.cellIndex] = 0;
                    cell.dragEndLockThis(null);
                });
            }

            if (isZaZhong) {
                if (currLockCells) {
                    currLockCells.forEach((cell) => {
                        GameDataMgr.getGameBag.bagArray[cell.cellData.cellIndex] = 0;
                        cell.dragEndLockThis(null);
                    });
                }

                if (checkResult.zaZhongPickCells && checkResult.zaZhongPickCells.length > 0) {
                    checkResult.zaZhongPickCells.forEach((cell) => {
                        GameDataMgr.getGameBag.bagArray[cell.cellData.cellIndex] = 1;
                        cell.dragEndLockThis(this.currPickNodeComp);
                    });
                    this.currPickNodeComp.dragEndLockCell(checkResult.zaZhongPickCells);

                    this.currPickNode.parent = this.auto_ui.node_DragEndNode;
                    const firstCellWorldPos = checkResult.zaZhongPickCells[0].node.convertToWorldSpaceAR(cc.v2(0, 0));
                    const equipWorldPos = this.currPickNodeComp
                        .getGridNode()
                        .children[0].convertToWorldSpaceAR(cc.v2(0, 0));
                    const offset = cc.v2(
                        firstCellWorldPos.x - equipWorldPos.x,
                        firstCellWorldPos.y - equipWorldPos.y
                    );
                    const targetPos = cc.v2(
                        this.currPickNode.x + offset.x,
                        this.currPickNode.y + offset.y
                    );

                    if (zaZhongWorldPos) {
                        targetPos.set(
                            this.currPickNodeComp.node.parent.convertToNodeSpaceAR(
                                zaZhongWorldPos
                            )
                        );
                        console.error(targetPos);
                    }

                    this.currPickNode.runAction(
                        cc.moveTo(this.xifuTime, targetPos.x, targetPos.y)
                    );
                    this.addDressUpData(this.currPickNodeComp, targetPos);
                } else {
                    this.addEquipPoolData(this.currPickNodeComp);
                    this.backToDady(this.currPickNodeComp, () => {
                        this.checkUpLevelLabel(equipComp);
                    });
                }
            } else {
                if (currLockCells) {
                    currLockCells.forEach((cell) => {
                        GameDataMgr.getGameBag.bagArray[cell.cellData.cellIndex] = 0;
                        cell.dragEndLockThis(null);
                    });
                    this.currPickNodeComp.dragEndLockCell(null);
                    this.removeDressUplData(this.currPickNode.uuid);
                    this.addEquipPoolData(this.currPickNodeComp);
                }

                this.removeEquipPoolData(checkResult.otherEquip.node.uuid);
                this.backToDady(this.currPickNodeComp, () => {
                    this.checkUpLevelLabel(equipComp);
                });
            }
        }

        this.recycleEquip(checkResult.otherEquip.node);
    }

    checkCellIsOk(e: any): any {
        let otherEquip: any;
        let zaZhongPickCells: any;
        const self = this;
        const currGeZi = this.currPickNodeComp.getGridNode();
        let isOk = true;
        let effectPos: cc.Vec2 | null = null;
        let pickCellArray: any[] = [];
        const zaZhongPickCellsArray: any[] = [];
        let nodeCubeFather = this.auto_ui.node_cubeFather;
        const bagArray = GameDataMgr.getGameBag.bagArray;

        if (this.currPickNodeComp.isGeZiType) {
            nodeCubeFather = this.auto_ui.node_cubeBaseFather;
        }

        const worldPositions: cc.Vec2[] = [];
        for (let i = 0; i < nodeCubeFather.childrenCount; i++) {
            const child = nodeCubeFather.children[i];
            worldPositions.push(child.convertToWorldSpaceAR(cc.v2(0, 0)));
        }

        for (let i = 0; i < currGeZi.childrenCount; i++) {
            const currGeZiChildPos = currGeZi.children[i].convertToWorldSpaceAR(cc.v2(0, 0));
            let found = false;

            const checkChild = (index: number): "continue" | "break" | undefined => {
                let cellIndex: number;
                if (self.currPickNodeComp.isGeZiType) {
                    cellIndex = index;
                } else {
                    cellIndex = nodeCubeFather.children[index].getComponent(ItemGameBagCell).cellData.cellIndex;
                }

                if (self.currPickNodeComp.isGeZiType) {
                    let isOccupied = false;
                    if (self.currAddCellDataMap.size > 0) {
                        self.currAddCellDataMap.forEach((cellData) => {
                            if (
                                cellData.cellNode !== self.currPickNode &&
                                cellData.pickCellArray &&
                                !isOccupied
                            ) {
                                for (let j = 0; j < cellData.pickCellArray.length; j++) {
                                    const pickCell = cellData.pickCellArray[j];
                                    if (cellIndex === pickCell.cellData.cellIndex) {
                                        isOccupied = true;
                                        break;
                                    }
                                }
                            }
                        });
                    }
                    if (isOccupied) {
                        return "continue";
                    }
                }

                const isOccupiedInBag = bagArray[cellIndex] !== -1 && !self.currPickNodeComp.isGeZiType;
                const isEmptyInBag = bagArray[cellIndex] === -1 && self.currPickNodeComp.isGeZiType;

                if (
                    (isOccupiedInBag || isEmptyInBag) &&
                    cc.Vec2.distance(currGeZiChildPos, worldPositions[index]) <
                    self.effectMax
                ) {
                    found = true;
                    zaZhongPickCellsArray.push(cellIndex);
                    if (!effectPos) {
                        effectPos = cc.v2(
                            worldPositions[index].x - currGeZiChildPos.x,
                            worldPositions[index].y - currGeZiChildPos.y
                        );
                    }
                    return "break";
                }
            };

            for (let j = 0; j < nodeCubeFather.childrenCount && "break" !== checkChild(j); j++) { }

            if (!found) {
                isOk = false;
            }
        }

        if (this.lastPickArray.length > 0) {
            this.lastPickArray.forEach((cell) => {
                cell.updateBgNodeColor(cc.Color.WHITE);
            });
        }
        this.lastPickArray.length = 0;

        zaZhongPickCellsArray.forEach((cellIndex) => {
            const cellComp = self.currPickNodeComp.isGeZiType
                ? self.baseCellCompArray[cellIndex]
                : self.cellCompMap.get(cellIndex);
            cellComp.updateBgNodeColor(isOk ? cc.Color.GREEN : cc.Color.RED);
            self.lastPickArray.push(cellComp);
            pickCellArray.push(cellComp);
        });

        const isMaxLevel =
            this.currPickNodeComp.equipData.equipLevel ===
            GameGlobalVariable.normalMaxLevel - 1;

        if (
            isOk &&
            !this.currPickNodeComp.isGeZiType &&
            pickCellArray.length > 0 &&
            this.currPickNodeComp.equipData.equipLevel <
            LogicGetEquip.getInstance.getMaxLevel(this.currPickNodeComp.equipData.shuiguoId) -
            1
        ) {
            let canUpgrade = true;

            if (isMaxLevel) {
                canUpgrade = false;
                const checkEquip = (index: number): "break" | undefined => {
                    const cellComp = pickCellArray[index];
                    if (
                        cellComp.equipComp &&
                        cellComp.equipComp.equipData.equipLevel ===
                        self.currPickNodeComp.equipData.equipLevel &&
                        LogicGetEquip.getInstance.getZaZhongId(
                            cellComp.equipComp.equipData.shuiguoId
                        ) === self.currPickNodeComp.equipData.shuiguoId
                    ) {
                        canUpgrade = true;
                        otherEquip = cellComp.equipComp;
                        if (e && pickCellArray && pickCellArray.length > 0) {
                            const otherEquips: any[] = [];
                            pickCellArray.forEach((cell) => {
                                if (
                                    cell &&
                                    cell.equipComp &&
                                    cell.equipComp !== self.currPickNodeComp &&
                                    cell.equipComp !== otherEquip &&
                                    !otherEquips.includes(cell.equipComp)
                                ) {
                                    otherEquips.push(cell.equipComp);
                                }
                            });
                            otherEquips.forEach((equip) => {
                                self.removeDressUplData(equip.node.uuid);
                                self.addEquipPoolData(equip);
                                self.backToDady(equip);
                                if (equip.lockCellArray) {
                                    equip.lockCellArray.forEach((lockCell) => {
                                        GameDataMgr.getGameBag.bagArray[
                                            lockCell.cellData.cellIndex
                                        ] = 0;
                                        lockCell.dragEndLockThis(null);
                                    });
                                }
                                equip.dragEndLockCell(null);
                            });
                        }
                        zaZhongPickCells = pickCellArray;
                        pickCellArray = null;
                        return "break";
                    }
                };

                for (let i = 0; i < pickCellArray.length && "break" !== checkEquip(i); i++) { }
            } else {
                for (let i = 0; i < pickCellArray.length; i++) {
                    const cellComp = pickCellArray[i];
                    if (
                        !cellComp.equipComp ||
                        cellComp.equipComp.uuid === this.currPickNodeComp.uuid ||
                        cellComp.equipComp.equipData.equipLevel !==
                        this.currPickNodeComp.equipData.equipLevel
                    ) {
                        canUpgrade = false;
                        break;
                    }
                    if (
                        cellComp.equipComp.equipData.shuiguoId !==
                        this.currPickNodeComp.equipData.shuiguoId &&
                        cellComp.equipComp.equipData.equipLevel <
                        GameGlobalVariable.normalMaxLevel - 1
                    ) {
                        canUpgrade = false;
                        break;
                    }
                }
            }

            if (canUpgrade && !otherEquip) {
                otherEquip = pickCellArray[0].equipComp;
                pickCellArray = null;
            }
        }

        let maxDistance: number;
        if (isMaxLevel) {
            maxDistance = 200;
        } else {
            maxDistance = 100;
        }

        if (!isOk && !this.currPickNodeComp.isGeZiType) {
            pickCellArray = null;
            const currPickNodePos = this.currPickNode.convertToWorldSpaceAR(cc.v2(0, 0));
            this.equipPool.forEach((equip) => {
                if (!otherEquip) {
                    const equipNodePos = equip.node.convertToWorldSpaceAR(cc.v2(0, 0));
                    if (
                        equip.node.uuid !== self.currPickNode.uuid &&
                        self.currPickNodeComp.equipData.equipLevel <
                        LogicGetEquip.getInstance.getMaxLevel(
                            self.currPickNodeComp.equipData.shuiguoId
                        ) -
                        1 &&
                        equip.equipData.equipLevel ===
                        self.currPickNodeComp.equipData.equipLevel &&
                        cc.Vec2.distance(equipNodePos, currPickNodePos) < maxDistance
                    ) {
                        if (
                            !(
                                equip.equipData.shuiguoId !==
                                self.currPickNodeComp.equipData.shuiguoId &&
                                equip.equipData.equipLevel <
                                GameGlobalVariable.normalMaxLevel - 1
                            ) &&
                            !(
                                LogicGetEquip.getInstance.getZaZhongId(
                                    equip.equipData.shuiguoId
                                ) !== self.currPickNodeComp.equipData.shuiguoId &&
                                equip.equipData.equipLevel ===
                                GameGlobalVariable.normalMaxLevel - 1
                            )
                        ) {
                            otherEquip = equip;
                            isOk = true;
                            effectPos = cc.v2(
                                equipNodePos.x - currPickNodePos.x,
                                equipNodePos.y - currPickNodePos.y
                            );
                        }
                    }
                }
            });

            if (!otherEquip) {
                this.dressUpEquipMap.forEach((equip, uuid) => {
                    if (!otherEquip) {
                        const equipNodePos = equip.node.convertToWorldSpaceAR(cc.v2(0, 0));
                        if (
                            uuid !== self.currPickNode.uuid &&
                            self.currPickNodeComp.equipData.equipLevel <
                            LogicGetEquip.getInstance.getMaxLevel(
                                self.currPickNodeComp.equipData.shuiguoId
                            ) -
                            1 &&
                            equip.equipData.equipLevel ===
                            self.currPickNodeComp.equipData.equipLevel &&
                            cc.Vec2.distance(equipNodePos, currPickNodePos) < maxDistance
                        ) {
                            if (
                                !(
                                    equip.equipData.shuiguoId !==
                                    self.currPickNodeComp.equipData.shuiguoId &&
                                    equip.equipData.equipLevel <
                                    GameGlobalVariable.normalMaxLevel - 1
                                ) &&
                                !(
                                    LogicGetEquip.getInstance.getZaZhongId(
                                        equip.equipData.shuiguoId
                                    ) !== self.currPickNodeComp.equipData.shuiguoId &&
                                    equip.equipData.equipLevel ===
                                    GameGlobalVariable.normalMaxLevel - 1
                                )
                            ) {
                                otherEquip = equip;
                                isOk = true;
                                effectPos = cc.v2(
                                    equipNodePos.x - currPickNodePos.x,
                                    equipNodePos.y - currPickNodePos.y
                                );
                            }
                        }
                    }
                });
            }
        }

        return {
            isOk,
            effectPos,
            pickCellArray,
            otherEquip,
            zaZhongPickCells
        };
    }

    private recycleEquip(node: cc.Node): void {
        node.destroy();
    }

    private getEquipNode(pfbName: string): cc.Node {
        const equipNode = this.auto_ui.node_EquipFather.getChildByName(pfbName);
        return equipNode ? cc.instantiate(equipNode) : null;
    }

    private removeEquipPoolData(uuid: string): void {
        const equipComp = this.equipPool.get(uuid);
        if (equipComp) {
            const equipData = equipComp.equipData;
            for (let i = 0; i < GameDataMgr.getGameBag.equipPool.length; i++) {
                const data = GameDataMgr.getGameBag.equipPool[i];
                if (
                    data.equipLevel === equipData.equipLevel &&
                    data.shuiguoId === equipData.shuiguoId &&
                    this.comparisonArray(data.lockCellIndex, equipData.lockCellIndex)
                ) {
                    GameDataMgr.getGameBag.equipPool.splice(i, 1);
                    break;
                }
            }
            this.equipPool.delete(uuid);
        }
    }

    private addEquipPoolData(equipComp: ItemGameEquip): void {
        equipComp.equipData.wPostion = null;
        this.equipPool.set(equipComp.node.uuid, equipComp);
        GameDataMgr.getGameBag.equipPool.push(equipComp.equipData);
    }

    private removeDressUplData(uuid: string): void {
        const equipComp = this.dressUpEquipMap.get(uuid);
        if (equipComp) {
            const equipData = equipComp.equipData;
            for (let i = 0; i < GameDataMgr.getGameBag.dressUpEquips.length; i++) {
                const data = GameDataMgr.getGameBag.dressUpEquips[i];
                if (
                    data.equipLevel === equipData.equipLevel &&
                    data.shuiguoId === equipData.shuiguoId &&
                    this.comparisonArray(data.lockCellIndex, equipData.lockCellIndex)
                ) {
                    GameDataMgr.getGameBag.dressUpEquips.splice(i, 1);
                    break;
                }
            }
            this.dressUpEquipMap.delete(uuid);
        }
    }

    private addDressUpData(equipComp: ItemGameEquip, pos: cc.Vec2): void {
        equipComp.equipData.wPostion = this.auto_ui.node_DragEndNode.convertToWorldSpaceAR(cc.v2(pos.x, pos.y - this.viewNodePosY));
        LogMgr.debug(equipComp.equipData.wPostion, pos);
        this.dressUpEquipMap.set(equipComp.node.uuid, equipComp);
        GameDataMgr.getGameBag.dressUpEquips.push(equipComp.equipData);
    }

    private comparisonArray(arr1: number[], arr2: number[]): boolean {
        return (
            (arr1 === null && arr2 === null) ||
            (arr1 !== null &&
                arr2 !== null &&
                arr1.length === arr2.length &&
                arr1.every((value) => arr2.indexOf(value) !== -1))
        );
    }

    private saveData(): void {
        GameDataMgr.saveGameBagData();
        EventMgrInstance.emitEvent(EVENT_TYPE.GAME_UPDATE_BAG);
    }

    private setCellFatherMove(canMove: boolean): void {
        this.cellFatherMove.setMoveability(canMove, this.auto_ui.node_bottomBtn.active);
        this.auto_ui.node_bottomBtn.active = !canMove;
        this.auto_ui.btn_UseGeZiBtn.node.active = canMove;
        this.auto_ui.node_useGeZiTip.active = canMove;
        this.auto_ui.btn_VideoGetCell.node.active = !canMove;

        if (canMove) {
            this.auto_ui.node_useGeZiTip.stopAllActions();
            this.auto_ui.node_useGeZiTip.runAction(
                cc.repeatForever(
                    cc.sequence(
                        cc.scaleTo(1, 0.8, 0.8),
                        cc.scaleTo(1, 0.7, 0.7)
                    )
                )
            );
        }

        if (
            PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) ===
            GameBagGuideIndex.GridGuide8 &&
            canMove
        ) {
            this.auto_ui.btn_UseGeZiBtn.interactable = false;
        } else {
            this.auto_ui.btn_UseGeZiBtn.interactable = true;
        }

        this.equipPool.forEach((equipComp) => {
            if (!equipComp.isGeZiType) {
                equipComp.setClickable(!canMove, true);
            }
        });

        this.dressUpEquipMap.forEach((equipComp) => {
            equipComp.setClickable(!canMove, true);
        });

        if (canMove) {
            this.auto_ui.node_cubeBaseFather.opacity = 255;
        } else {
            this.auto_ui.node_cubeBaseFather.opacity = 0;
            if (this.currAddCellDataMap.size > 0) {
                this.checkDragCellIsOk();
                this.currAddCellDataMap.forEach((data) => {
                    data.pickCellArray.forEach((cell) => {
                        GameDataMgr.getGameBag.bagArray[cell.cellData.cellIndex] = 0;
                        const baseCell = this.baseCellCompArray[cell.cellData.cellIndex]
                            .node;
                        const newCell = cc.instantiate(baseCell);
                        newCell.parent = this.auto_ui.node_cubeFather;
                        newCell.setPosition(
                            newCell.parent.convertToNodeSpaceAR(
                                baseCell.convertToWorldSpaceAR(cc.v2(0, 0))
                            )
                        );
                        this.cellCompMap.set(
                            cell.cellData.cellIndex,
                            newCell.getComponent(ItemGameBagCell)
                        );
                        this.cellCompMap
                            .get(cell.cellData.cellIndex)
                            .initializeSettings(cell.cellData, true);
                        newCell.name = `方块${cell.cellData.cellIndex}`;
                    });
                    this.removeEquipPoolData(data.cellNode.uuid);
                    this.recycleEquip(data.cellNode);
                });

                const spacing = cc.v2(44, 32);
                const offset = this.changeSizeByChild(
                    this.auto_ui.node_cubeFather,
                    spacing
                );
                this.dressUpEquipMap.forEach((equipComp) => {
                    equipComp.node.x += offset.x;
                    equipComp.node.y += offset.y;
                });
                this.currAddCellDataMap.clear();
            }
        }

        this.setBgNodeSize(canMove);
        if (!canMove) {
            const maxVideoCellCount = GameGlobalVariable.bagVideoCellCount;
            this.auto_ui.btn_VideoGetCell.node.active =
                this.maxX * this.maxY - this.cellCompMap.size > 0 &&
                GameDataMgr.getGameBag.videoCellCount < maxVideoCellCount;
        }
    }

    public moveChangeBagCellIndex(
        result: {
            isOk: boolean;
            pickCellArray: ItemGameBagCell[];
        }
    ): void {
        if (result && result.isOk) {
            const equipComps: ItemGameEquip[] = [];
            this.auto_ui.node_cubeFather.children.forEach((child, index) => {
                const cellComp = child.getComponent(ItemGameBagCell);
                if (!result.pickCellArray[index]) {
                    result.pickCellArray[index];
                }
                child.name = `方块${result.pickCellArray[index]}`;
                cellComp.updateCellData({
                    cellIndex: result.pickCellArray[index],
                });
                if (cellComp.equipComp && equipComps.indexOf(cellComp.equipComp) === -1) {
                    equipComps.push(cellComp.equipComp);
                }
            });

            GameDataMgr.getGameBag.equipPool = [];
            equipComps.forEach((equipComp) => {
                const lockCells = equipComp.lockCellArray!;
                const lockCellIndexes: number[] = [];
                lockCells.forEach((cell) => {
                    lockCellIndexes.push(cell.cellData.cellIndex);
                });
                equipComp.equipData.lockCellIndex = lockCellIndexes;
                GameDataMgr.getGameBag.equipPool.push(equipComp.equipData);
            });

            const cellComps: ItemGameBagCell[] = [];
            this.cellCompMap.forEach((cellComp) => {
                cellComps.push(cellComp);
            });
            this.cellCompMap.clear();
            cellComps.forEach((cellComp) => {
                this.cellCompMap.set(cellComp.cellData.cellIndex, cellComp);
            });

            const bagArray = GameDataMgr.getGameBag.bagArray;
            for (let i = 0; i < bagArray.length; i++) {
                if (this.cellCompMap.has(i)) {
                    GameDataMgr.getGameBag.bagArray[i] = this.cellCompMap.get(i)!.equipComp
                        ? 1
                        : 0;
                } else {
                    GameDataMgr.getGameBag.bagArray[i] = -1;
                }
            }
        }
    }

    private checkDragCellIsOk(): void {
        const cellArrays: number[][] = [];
        const uuids: string[] = [];

        this.currAddCellDataMap.forEach((data, uuid) => {
            const cellIndexes: number[] = [];
            data.pickCellArray.forEach((cell) => {
                cellIndexes.push(cell.cellData.cellIndex);
            });
            cellArrays.push(cellIndexes);
            uuids.push(uuid);
        });

        const bagArray = GameDataMgr.getGameBag.bagArray;
        for (let i = 0; i < cellArrays.length; i++) {
            for (let j = 0; j < cellArrays.length; j++) {
                const cellArray = cellArrays[j];
                if (cellArray && this.checkOneCellArrayIsOk(cellArray, bagArray)) {
                    cellArray.forEach((cellIndex) => { bagArray[cellIndex] = 0; });
                    cellArrays[j] = null;
                    uuids[j] = null;
                }
            }
        }

        if (!uuids.every((uuid) => uuid === null)) {
            TipMgr.showToast("请将扩展格放置在相邻地块");
        }

        uuids.forEach((uuid) => {
            if (uuid) {
                const equipComp = this.equipPool.get(uuid);
                this.backToDady(equipComp!);
                if (equipComp!.lockCellArray) {
                    equipComp!.lockCellArray.forEach((cell) => {
                        cell.dragEndLockThis(null);
                    });
                    equipComp!.dragEndLockCell(null);
                }
            }
            this.currAddCellDataMap.delete(uuid);
        });
    }

    private checkOneCellArrayIsOk(
        cellArray: number[],
        bagArray: number[]
    ): boolean {
        let isOk = false;
        for (let i = 0; i < cellArray.length; i++) {
            const cellIndex = cellArray[i];
            let hasAdjacentCell = false;
            if (
                (cellIndex - 1 >= 0 &&
                    (cellIndex - 1) % this.maxX !== this.maxX - 1 &&
                    bagArray[cellIndex - 1] >= 0) ||
                (cellIndex - this.maxX >= 0 && bagArray[cellIndex - this.maxX] >= 0) ||
                (cellIndex + 1 < bagArray.length &&
                    (cellIndex + 1) % this.maxX !== 0 &&
                    bagArray[cellIndex + 1] >= 0) ||
                (cellIndex + this.maxX < bagArray.length && bagArray[cellIndex + this.maxX] >= 0)
            ) {
                hasAdjacentCell = true;
            }
            if (hasAdjacentCell) {
                isOk = true;
                break;
            }
        }
        return isOk;
    }

    private setBgNodeSize(isMove: boolean): void {
        this.scheduleOnce(() => {
            this.auto_ui.node_diTuNode.active = true;
            if (isMove) {
                this.auto_ui.node_diTuNode.width =
                    this.auto_ui.node_cubeBaseFather.width;
                this.auto_ui.node_diTuNode.height =
                    this.auto_ui.node_cubeBaseFather.height;
                this.auto_ui.node_diTuNode.setAnchorPoint(
                    this.auto_ui.node_cubeBaseFather.getAnchorPoint()
                );
                this.auto_ui.node_diTuNode.setPosition(
                    this.auto_ui.node_cubeBaseFather.getPosition()
                );
            } else {
                this.auto_ui.node_cubeFather.setPosition(0, 0);
                const width = this.auto_ui.node_cubeFather.width;
                const height = this.auto_ui.node_cubeFather.height;
                this.auto_ui.node_diTuNode.width = width;
                this.auto_ui.node_diTuNode.height = height;
                this.auto_ui.node_diTuNode.setPosition(0, 0);
                this.auto_ui.node_DragEndNode.setPosition(0, 0);
                this.dressUpEquipMap.forEach((equipComp) => {
                    equipComp.equipData.wPostion = equipComp.node.convertToWorldSpaceAR(
                        cc.v2(0, -1 * this.viewNodePosY)
                    );
                });
                this.SaveCellWpos();
            }
        });
    }

    private changeSizeByChild(node: cc.Node, spacing: cc.Vec2): cc.Vec2 {
        let minX = 10000;
        let maxX = -10000;
        let minY = 10000;
        let maxY = -10000;
        const childWorldPositions: cc.Vec2[] = [];

        for (let i = 0; i < node.children.length; i++) {
            const child = node.children[i];
            const worldPos = child.convertToWorldSpaceAR(cc.v2(0, 0));
            if (worldPos.x - child.width / 2 < minX) {
                minX = worldPos.x - child.width / 2;
            }
            if (worldPos.x + child.width / 2 > maxX) {
                maxX = worldPos.x + child.width / 2;
            }
            if (worldPos.y - child.height / 2 < minY) {
                minY = worldPos.y - child.height / 2;
            }
            if (worldPos.y + child.height / 2 > maxY) {
                maxY = worldPos.y + child.height / 2;
            }
            childWorldPositions.push(worldPos);
        }

        const width = maxX - minX + spacing.x;
        const height = maxY - minY + spacing.y;
        node.width = width;
        node.height = height;

        const oldWorldPos = node.convertToWorldSpaceAR(cc.v2(0, 0));
        const newWorldPos = cc.v2((maxX + minX) / 2, (maxY + minY) / 2);
        node.setPosition(node.parent.convertToNodeSpaceAR(newWorldPos));

        for (let i = 0; i < node.children.length; i++) {
            const child = node.children[i];
            child.setPosition(node.convertToNodeSpaceAR(childWorldPositions[i]));
        }

        return cc.v2(oldWorldPos.x - newWorldPos.x, oldWorldPos.y - newWorldPos.y);
    }

    private SaveCellWpos(): void {
        const cellWposArray: cc.Vec2[] = [];
        this.auto_ui.node_cubeFather.children.forEach((child) => {
            cellWposArray.push(
                child.convertToWorldSpaceAR(cc.v2(0, -1 * this.viewNodePosY))
            );
        });
        GameDataMgr.getGameBag.cellWposArray = cellWposArray;
        GameDataMgr.saveGameBagData();
        EventMgrInstance.emitEvent(EVENT_TYPE.GAME_UPDATE_BAG);
    }

    private backToDady(
        equipComp: ItemGameEquip,
        callback?: () => void
    ): void {
        const worldPos = equipComp.node.convertToWorldSpaceAR(cc.v2(0, 0));
        let siblingIndex = this.auto_ui.node_DragFather.children.length;
        for (let i = 0; i < this.auto_ui.node_DragFather.children.length; i++) {
            const childWorldPos = this.auto_ui.node_DragFather.children[
                i
            ].convertToWorldSpaceAR(cc.v2(0, 0));
            if (worldPos.x < childWorldPos.x) {
                siblingIndex = i;
                break;
            }
        }

        const equipIcon = equipComp.equipIcon;
        equipIcon.parent = this.auto_ui.node_DragTempNode;
        equipIcon.setPosition(
            equipIcon.parent.convertToNodeSpaceAR(worldPos)
        );

        equipComp.node.parent = this.auto_ui.node_DragFather;
        equipComp.node.setSiblingIndex(siblingIndex);
        equipComp.node.setPosition(0, 0);
        equipComp.setClickable(false);

        equipComp.scheduleOnce(() => {
            equipIcon.parent = equipComp.node;
            equipIcon.setPosition(equipIcon.parent.convertToNodeSpaceAR(worldPos));

            const randomValue = Math.random();
            let angle = 0;
            if (randomValue > 0.66) {
                angle = 20;
            } else if (randomValue < 0.33) {
                angle = -20;
            }

            equipIcon.runAction(
                cc.sequence(
                    cc.spawn(
                        cc.moveTo(this.moveTime, 0, 0),
                        cc.rotateTo(this.moveTime, angle)
                    ),
                    cc.delayTime(0.15),
                    cc.callFunc(() => {
                        equipComp.setClickable(true);
                        equipComp.node.angle = equipIcon.angle;
                        equipIcon.angle = 0;
                        if (callback) {
                            callback();
                        }
                    })
                )
            );
        });

        this.checkDragFatherLayout();
    }

    private showDragBone(worldPos: cc.Vec2): void {
        const boneNode = this.auto_ui.dbAnim_heChengEffect.node;
        boneNode.setPosition(
            boneNode.parent.convertToNodeSpaceAR(worldPos)
        );
        boneNode.active = true;
        this.auto_ui.dbAnim_heChengEffect.playAnimation(
            "newAnimation",
            1
        );
    }

    private makePaiZi(parent: cc.Node): ItemPaiZi {
        const paiZiNode = cc.instantiate(this.paiZiPfb);
        paiZiNode.parent = parent;
        return paiZiNode.getComponent(ItemPaiZi);
    }

    private checkDragFatherLayout(
        uuid?: string,
        count: number = 0
    ): void {
        let spacing = 30;
        const layout = this.auto_ui.node_DragFather.getComponent(
            cc.Layout
        );
        const equipCount = this.equipPool.size + count;

        if (equipCount >= 3) {
            let totalWidth = 0;
            this.equipPool.forEach((equipComp) => {
                if (!(uuid && uuid === equipComp.node.uuid)) {
                    totalWidth += equipComp.node.width;
                }
            });

            if (totalWidth > 700) {
                spacing = Math.floor(
                    (700 - totalWidth) / (equipCount - 1)
                );
            }
        }

        if (layout.spacingX !== spacing) {
            layout.spacingX = spacing;
            layout.updateLayout();
        }
    }

    private checkDressUpLabel(equipComp: ItemGameEquip): void {
        if (this.firstUseArray.indexOf(equipComp.equipData.shuiguoId) === -1) {
            this.firstUseArray.push(equipComp.equipData.shuiguoId);
            const shuiguoData = Excel.shuiguo(equipComp.equipData.shuiguoId);
            const worldPos = equipComp.node.convertToWorldSpaceAR(
                cc.v2(0, 0)
            );
            worldPos.y += 0.7 * equipComp.node.height;
            const labelStr = `<color=#ffffff>${shuiguoData.starWord}</c>`;
            this.showTipNode(labelStr, worldPos, 1.5);

            const randomIndex = Math.floor(
                Math.random() * 5
            );
            AudioMgr.playSoundEffect(
                `sound/dressUp${randomIndex + 1}`,
                false,
                BundleNames.Game
            );
        }
    }

    private checkUpLevelLabel(equipComp: ItemGameEquip): void {
        if (
            equipComp.equipData.equipLevel !== GameGlobalVariable.normalMaxLevel
        ) {
            let labelStr = "";
            const shuiguoId = equipComp.equipData.shuiguoId;
            let duration = 1.5;

            if (
                LogicGetEquip.getInstance.getMaxLevel(shuiguoId) ===
                GameGlobalVariable.zaZhongMaxLevel &&
                equipComp.equipData.equipLevel ===
                GameGlobalVariable.normalMaxLevel - 1 &&
                LogicGetEquip.getInstance.getMaxLevel(
                    this.currPickNodeComp.equipData.shuiguoId
                ) === GameGlobalVariable.zaZhongMaxLevel
            ) {
                const shuiguoData = Excel.shuiguo(shuiguoId);
                const zaZhongData = Excel.shuiguo(
                    LogicGetEquip.getInstance.getZaZhongId(shuiguoId)
                );
                const iconName = `player${(shuiguoData.jinjieShuiGuoId !== 0 ? shuiguoData : zaZhongData).id -
                    1000
                    }_5`;
                labelStr = `<color=#ffffff>可与4阶${zaZhongData.name
                    }杂交合成至5阶</c><img src='${iconName}'/>`;
                duration = 3.5;
            } else {
                const upData = LogicGetEquip.getInstance.getEquipUpData(
                    shuiguoId,
                    equipComp.equipData.equipLevel
                );
                if (upData.addattack !== 0) {
                    if (shuiguoId === FruitId.辣妹子) {
                        labelStr += "<color=#ffffff>攻击速度光环 + </c><color=#00ff00>100</c> <color=#ffffff>%</c>";
                    } else {
                        labelStr += "<color=#ffffff>攻击力 + </c><color=#00ff00>100</c> <color=#ffffff>%</c>";
                    }
                }
                if (upData.addattackspeed !== 0) {
                    labelStr += "<color=#ffffff>技能速度 + </c><color=#00ff00>100</c> <color=#ffffff>%</c>";
                }
                if (upData.addbeidongbuff.length > 0 && upData.addbeidongbuff[0] !== 0) {
                    if (shuiguoId === FruitId.招财橙子) {
                        labelStr += "<color=#ffffff>产出银币翻倍</c>";
                    } else if (shuiguoId === FruitId.柠檬精) {
                        labelStr += "<color=#ffffff>攻击力光环 + </c><color=#00ff00>100 <color=#ffffff>%</c>";
                    } else {
                        labelStr += "<color=#ffffff>天赋加成效果翻倍</c>";
                    }
                }
            }

            if (labelStr) {
                const worldPos = equipComp.node.convertToWorldSpaceAR(cc.v2(0, 0));
                worldPos.y += 0.7 * equipComp.node.height;
                this.showTipNode(labelStr, worldPos, duration);
            }
        }
    }

    private showTipNode(labelStr: string, worldPos: cc.Vec2, duration: number): void {
        labelStr = `<outline color=#000000 width=3>${labelStr}</outline>`;
        this.auto_ui.rtxt_upTipLabel.string = labelStr;

        const tipNode = this.auto_ui.node_upTipNode;
        tipNode.stopAllActions();
        tipNode.opacity = 255;
        tipNode.active = true;
        tipNode.setPosition(tipNode.parent.convertToNodeSpaceAR(worldPos));
        tipNode.children[0].x = 0;

        if (tipNode.x > 215) {
            tipNode.children[0].x = 215 - tipNode.x;
        } else if (tipNode.x < -215) {
            tipNode.children[0].x = -215 - tipNode.x;
        }

        tipNode.runAction(
            cc.sequence(
                cc.delayTime(duration),
                cc.fadeOut(0.25),
                cc.callFunc(() => {
                    tipNode.active = false;
                })
            )
        );
    }

    private checkGuide(): void {
        if (
            PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) !==
            GameBagGuideIndex.GuideCompletion
        ) {
            this.auto_ui.btn_VideoGetCell.node.active = false;
            this.auto_ui.node_bottomBtn.children.forEach((child) => (child.scale = 1));
            GameGlobalVariable.isFirstGuide = true;
        }

        this.scheduleOnce(() => {
            switch (
            PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag)
            ) {
                case GameBagGuideIndex.InitialGuide1:
                    this.showGuide1();
                    break;
                case GameBagGuideIndex.DragFruitGuide2:
                    this.showGuide2();
                    break;
                case GameBagGuideIndex.RefreshButtonGuide3:
                    this.showGuide3();
                    break;
                case GameBagGuideIndex.SynthesisGuide4:
                    this.showGuide4();
                    break;
                case GameBagGuideIndex.StartBattleGuide6:
                    this.showGuide6();
                    break;
                case GameBagGuideIndex.GridGuide8:
                    this.showGuide8();
                    break;
                case GameBagGuideIndex.OtherFruitsGuide9:
                    this.showGuide9();
                    break;
                case GameBagGuideIndex.GuideEnd10:
                    this.showGuide10();
                    break;
            }
        });
    }

    private showGuide1(): void {
        GuideCtrlInstance.showGuide({
            callBack: () => {
                PlayerDataMgr.setGuideIndex(
                    GuideName.GameBag,
                    GameBagGuideIndex.DragFruitGuide2
                );
                this.showGuide2();
            },
            sayStr: "怪物大军即将到来，赶快布置水果勇士，准备迎战吧！",
            showTipNode: true,
        });
        this.auto_ui.node_bottomBtn.active = false;
    }

    private showGuide2(): void {
        this.auto_ui.node_bottomBtn.active = false;
        if (this.equipPool.size > 0) {
            let equipNode = this.auto_ui.node_DragFather.children[0];
            if (!equipNode) {
                this.equipPool.forEach((equipComp) => {
                    equipNode = equipComp.node;
                });
            }
            const worldPos = equipNode.convertToWorldSpaceAR(cc.v2(0, 0));
            const nodePos = this.node.convertToNodeSpaceAR(worldPos);

            GuideCtrlInstance.showOneFingerGuide({
                parent: this.node,
                isWillClickClose: false,
                x: nodePos.x,
                y: nodePos.y,
                getFingerCallBack: (fingerNode) => {
                    this.guideShou = fingerNode;
                    nodePos.x *= -1;
                    nodePos.y *= -1;
                    nodePos.normalizeSelf();
                    fingerNode.runAction(
                        cc.repeatForever(
                            cc.sequence(
                                cc.moveTo(1.5, fingerNode.x + 200 * nodePos.x, fingerNode.y + 500 * nodePos.y),
                                cc.moveTo(0.02, fingerNode.x, fingerNode.y)
                            )
                        )
                    );
                },
            });

            if (!this.selfMap["显示引导2的框"]) {
                this.selfMap["显示引导2的框"] = true;
                GuideCtrlInstance.showGuideMaskFrame("将商店中刷新出的装备，放入背包", this.node);
            }
        } else {
            PlayerDataMgr.setGuideIndex(
                GuideName.GameBag,
                GameBagGuideIndex.RefreshButtonGuide3
            );
            this.auto_ui.node_bottomBtn.active = true;
            this.auto_ui.btn_VideoResetBtn.node.active = false;
            this.auto_ui.btn_start.node.active = false;
            this.auto_ui.btn_ResetBtn.node.active = true;
            this.checkBottomBtnScale();
            this.auto_ui.btn_ResetBtn.node.children[0].y = -35;
            this.auto_ui.btn_ResetBtn.node.children[1].active = false;
            GuideCtrlInstance.showGuide({
                callBack: () => {
                    this.checkGuide();
                },
                sayStr: "刷新商店获得更多水果",
            });
        }
    }

    private showGuide3(): void {
        this.auto_ui.node_bottomBtn.active = true;
        this.auto_ui.btn_VideoResetBtn.node.active = false;
        this.auto_ui.btn_start.node.active = false;
        this.auto_ui.btn_ResetBtn.node.active = true;
        this.checkBottomBtnScale();
        this.auto_ui.btn_ResetBtn.node.children[0].y = -35;
        this.auto_ui.btn_ResetBtn.node.children[1].active = false;

        this.scheduleOnce(() => {
            const worldPos = this.auto_ui.btn_ResetBtn.node.convertToWorldSpaceAR(
                cc.v2(0, 0)
            );
            const size = cc.size(
                this.auto_ui.btn_ResetBtn.node.width,
                this.auto_ui.btn_ResetBtn.node.height
            );
            GuideCtrlInstance.showGuide({
                callBack: () => {
                    this.resetEquip(true, false, false);
                    PlayerDataMgr.setGuideIndex(
                        GuideName.GameBag,
                        GameBagGuideIndex.SynthesisGuide4
                    );
                    this.auto_ui.btn_ResetBtn.node.active = false;
                    this.checkGuide();
                    this.auto_ui.btn_ResetBtn.node.children[0].y = -12;
                    this.auto_ui.btn_ResetBtn.node.children[1].active = true;
                },
                wPos: worldPos,
                size: size,
            });
        });
    }

    private showGuide4(): void {
        this.auto_ui.node_bottomBtn.active = false;
        if (this.equipPool.size > 0) {
            this.guide4Time = -1;
            this.guideSGComp = null;
            this.dressUpEquipMap.forEach((equipComp) => equipComp.setClickable(false));
            this.equipPool.forEach((equipComp) => {
                equipComp.setClickable(false);
                if (!this.guideSGComp) {
                    switch (equipComp.equipData.shuiguoId) {
                        case FruitId.毒蘑菇:
                            this.guide4Time = 0;
                            this.guideSGComp = equipComp;
                            equipComp.setClickable(true);
                            break;
                        case FruitId.爆头瓜:
                            this.guide4Time = 1;
                            this.guideSGComp = equipComp;
                            equipComp.setClickable(true);
                            break;
                    }
                }
            });

            if (!this.guideSGComp) {
                this.equipPool.forEach((equipComp) => {
                    equipComp.setClickable(true);
                    this.guideSGComp = equipComp;
                });
                this.guide4Time = 2;
            }

            if (this.guideSGComp) {
                let targetWorldPos: cc.Vec2;
                this.dressUpEquipMap.forEach((equipComp) => {
                    if (equipComp.equipData.shuiguoId === this.guideSGComp.equipData.shuiguoId) {
                        targetWorldPos = equipComp.node.convertToWorldSpaceAR(cc.v2(0, 0));
                    }
                });

                const startWorldPos = this.guideSGComp.node.convertToWorldSpaceAR(cc.v2(0, 0));
                const startNodePos = this.node.convertToNodeSpaceAR(startWorldPos);

                if (!targetWorldPos) {
                    this.cellCompMap.forEach((cellComp) => {
                        if (!cellComp.equipComp) {
                            targetWorldPos = cellComp.node.convertToWorldSpaceAR(cc.v2(0, 0));
                        }
                    });
                }

                targetWorldPos.x -= startWorldPos.x;
                targetWorldPos.y -= startWorldPos.y;

                GuideCtrlInstance.showOneFingerGuide({
                    parent: this.node,
                    isWillClickClose: false,
                    x: startNodePos.x,
                    y: startNodePos.y,
                    getFingerCallBack: (fingerNode) => {
                        this.guideShou = fingerNode;
                        fingerNode.runAction(
                            cc.repeatForever(
                                cc.sequence(
                                    cc.moveTo(1.5, fingerNode.x + targetWorldPos.x, fingerNode.y + targetWorldPos.y),
                                    cc.moveTo(0.02, fingerNode.x, fingerNode.y)
                                )
                            )
                        );
                    },
                });
            }

            if (!this.selfMap["显示引导4的框"]) {
                this.selfMap["显示引导4的框"] = true;
                GuideCtrlInstance.showGuideMaskFrame("相同的装备可以合成升级", this.node);
            }
        } else {
            this.showGuide4_2();
        }
    }

    private showGuide4_2(): void {
        let targetNode: cc.Node;
        this.dressUpEquipMap.forEach((equipComp) => {
            if (equipComp.equipData.shuiguoId === FruitId.招财橙子) {
                targetNode = equipComp.node;
            }
        });

        if (targetNode) {
            const worldPos = targetNode.convertToWorldSpaceAR(cc.v2(0, 0));
            const size = cc.size(targetNode.width, targetNode.height);
            GuideCtrlInstance.showGuide({
                callBack: () => {
                    PlayerDataMgr.setGuideIndex(
                        GuideName.GameBag,
                        GameBagGuideIndex.StartBattleGuide6
                    );
                    this.checkGuide();
                },
                sayStr: "橘子会在每波结束后，额外产出银币",
                sayNodePos: cc.v2(0, 400),
                wPos: worldPos,
                size: size,
                btnIsMax: true,
            });
        }
    }

    private showGuide6(): void {
        this.auto_ui.node_bottomBtn.active = true;
        this.auto_ui.btn_ResetBtn.node.active = false;
        this.auto_ui.btn_start.node.active = true;
        this.auto_ui.btn_VideoResetBtn.node.active = false;
        this.checkBottomBtnScale();

        GuideCtrlInstance.showGuide({
            callBack: () => {
                const worldPos = this.auto_ui.btn_start.node.convertToWorldSpaceAR(
                    cc.v2(0, 0)
                );
                const size = cc.size(
                    this.auto_ui.btn_start.node.width,
                    this.auto_ui.btn_start.node.height
                );
                GuideCtrlInstance.showGuide({
                    wPos: worldPos,
                    size: size,
                    callBack: () => {
                        this.dressUpEquipMap.forEach((equipComp) => equipComp.setClickable(true));
                        this.equipPool.forEach((equipComp) => equipComp.setClickable(true));
                        this.auto_ui.btn_ResetBtn.node.active = true;
                        this.auto_ui.btn_start.node.active = true;
                        this.auto_ui.btn_VideoResetBtn.node.active = true;
                        this.auto_ui.node_bottomBtn.active = true;
                        this.checkBottomBtnScale();
                        PlayerDataMgr.setGuideIndex(
                            GuideName.GameBag,
                            GameBagGuideIndex.EntryGuide7
                        );
                        this.gameStart();
                    },
                });
            },
            sayStr: "已筹备齐全，快让水果勇士们参战吧！",
        });
    }

    private showGuide8(): void {
        this.equipPool.forEach((equipComp) => {
            if (!equipComp.isGeZiType) {
                equipComp.setClickable(false);
            }
        });
        this.dressUpEquipMap.forEach((equipComp) => {
            equipComp.setClickable(false);
        });

        this.equipPool.forEach((equipComp) => {
            if (equipComp.isGeZiType) {
                const worldPos = equipComp.node.convertToWorldSpaceAR(cc.v2(0, 0));
                const nodePos = this.node.convertToNodeSpaceAR(worldPos);
                const targetWorldPos = this.node.convertToWorldSpaceAR(cc.v2(0, 0));
                const offset = cc.v2(
                    targetWorldPos.x - worldPos.x,
                    targetWorldPos.y - worldPos.y
                );

                GuideCtrlInstance.showOneFingerGuide({
                    parent: this.node,
                    isWillClickClose: false,
                    x: nodePos.x,
                    y: nodePos.y,
                    getFingerCallBack: (fingerNode) => {
                        this.guideShou = fingerNode;
                        fingerNode.runAction(
                            cc.repeatForever(
                                cc.sequence(
                                    cc.moveTo(
                                        1.5,
                                        fingerNode.x + offset.x,
                                        fingerNode.y + offset.y
                                    ),
                                    cc.moveTo(0.02, fingerNode.x, fingerNode.y)
                                )
                            )
                        );
                    },
                });
            }
        });

        GuideCtrlInstance.showGuideMaskFrame(
            "出现扩展格子，赶紧将其拖放至相邻的空地处获得更大的空间吧！",
            this.node
        );
        this.auto_ui.node_bottomBtn.active = false;
    }

    private showGuide8_1(): void {
        this.auto_ui.btn_UseGeZiBtn.interactable = true;
        const worldPos = this.auto_ui.btn_UseGeZiBtn.node.convertToWorldSpaceAR(
            cc.v2(0, 0)
        );
        const size = cc.size(
            this.auto_ui.btn_UseGeZiBtn.node.width,
            this.auto_ui.btn_UseGeZiBtn.node.height
        );

        GuideCtrlInstance.showGuide({
            wPos: worldPos,
            size: size,
            callBack: () => {
                this.setCellFatherMove(false);
                PlayerDataMgr.setGuideIndex(
                    GuideName.GameBag,
                    GameBagGuideIndex.OtherFruitsGuide9
                );
                this.checkGuide();
            },
        });
    }

    private guideCheckCell(cells: ItemGameBagCell[]): boolean {
        const bagArray = GameDataMgr.getGameBag.bagArray;
        let isOk = false;

        for (let i = 0; i < cells.length; i++) {
            const cellIndex = cells[i].cellData.cellIndex;
            let hasAdjacentCell = false;

            if (
                (cellIndex - 1 >= 0 &&
                    (cellIndex - 1) % this.maxX !== this.maxX - 1 &&
                    bagArray[cellIndex - 1] >= 0) ||
                (cellIndex - this.maxX >= 0 && bagArray[cellIndex - this.maxX] >= 0) ||
                (cellIndex + 1 < bagArray.length &&
                    (cellIndex + 1) % this.maxX !== 0 &&
                    bagArray[cellIndex + 1] >= 0) ||
                (cellIndex + this.maxX < bagArray.length &&
                    bagArray[cellIndex + this.maxX] >= 0)
            ) {
                hasAdjacentCell = true;
            }

            if (hasAdjacentCell) {
                isOk = true;
                break;
            }
        }

        return isOk;
    }

    private showGuide9(): void {
        this.auto_ui.node_bottomBtn.active = false;

        if (this.equipPool.size > 0) {
            let equipNode = this.auto_ui.node_DragFather.children[0];
            if (!equipNode) {
                this.equipPool.forEach((equipComp) => {
                    equipNode = equipComp.node;
                });
            }

            const worldPos = equipNode.convertToWorldSpaceAR(cc.v2(0, 0));
            const nodePos = this.node.convertToNodeSpaceAR(worldPos);

            GuideCtrlInstance.showOneFingerGuide({
                parent: this.node,
                isWillClickClose: false,
                x: nodePos.x,
                y: nodePos.y,
                getFingerCallBack: (fingerNode) => {
                    this.guideShou = fingerNode;
                    nodePos.x *= -1;
                    nodePos.y *= -1;
                    nodePos.normalizeSelf();
                    fingerNode.runAction(
                        cc.repeatForever(
                            cc.sequence(
                                cc.moveTo(1.5, fingerNode.x + 200 * nodePos.x, fingerNode.y + 500 * nodePos.y),
                                cc.moveTo(0.02, fingerNode.x, fingerNode.y)
                            )
                        )
                    );
                },
            });
        } else {
            PlayerDataMgr.setGuideIndex(
                GuideName.GameBag,
                GameBagGuideIndex.GuideEnd10
            );
            this.checkGuide();
        }
    }

    private showGuide10(): void {
        this.auto_ui.btn_VideoResetBtn.node.active = true;
        this.auto_ui.btn_ResetBtn.node.active = true;
        this.auto_ui.btn_start.node.active = true;
        this.auto_ui.node_bottomBtn.active = true;
        this.checkBottomBtnScale();

        const worldPos = this.auto_ui.btn_ResetBtn.node.convertToWorldSpaceAR(
            cc.v2(0, 0)
        );
        const size = cc.size(
            this.auto_ui.btn_ResetBtn.node.width,
            this.auto_ui.btn_ResetBtn.node.height
        );

        GuideCtrlInstance.showGuide({
            callBack: () => {
                this.resetEquip(false, false, false);
                GuideCtrlInstance.showGuide({
                    callBack: () => {
                        PlayerDataMgr.setGuideIndex(
                            GuideName.GameBag,
                            GameBagGuideIndex.GuideCompletion
                        );
                        this.auto_ui.btn_VideoGetCell.node.active = true;
                        this.scheduleOnce(() => {
                            this.checkBottomBtnScale();
                        }, 0.15);
                    },
                    sayStr: "充分利用安排空地，做一个整理大师吧！",
                });
            },
            sayStr: "使用银币刷新商店，获得更多水果加强实力",
            wPos: worldPos,
            size: size,
        });
    }

    private checkUpBuff(cellIndexes: number[], isEnd: boolean): void {
        if (!this.isUpBuffCdTime && cellIndexes && cellIndexes.length !== 0) {
            this.isUpBuffCdTime = true;
            this.scheduleOnce(() => { this.isUpBuffCdTime = false; }, isEnd ? 0.2 : 0);

            const bagArray = GameDataMgr.getGameBag.bagArray;
            const adjacentCells: number[] = [];

            for (let i = 0; i < cellIndexes.length; i++) {
                const cellIndex = cellIndexes[i];
                if (
                    (cellIndex - 1 >= 0 && (cellIndex - 1) % this.maxX !== this.maxX - 1 && bagArray[cellIndex - 1] > 0) ||
                    (cellIndex - this.maxX >= 0 && bagArray[cellIndex - this.maxX] > 0)
                ) {
                    const adjacentIndex = cellIndex - 1;
                    if (cellIndexes.indexOf(adjacentIndex) === -1) {
                        adjacentCells.push(adjacentIndex);
                    }
                }
                if (cellIndex - this.maxX >= 0 && bagArray[cellIndex - this.maxX] > 0) {
                    const adjacentIndex = cellIndex - this.maxX;
                    if (cellIndexes.indexOf(adjacentIndex) === -1) {
                        adjacentCells.push(adjacentIndex);
                    }
                }
                if (cellIndex + 1 < bagArray.length && (cellIndex + 1) % this.maxX !== 0 && bagArray[cellIndex + 1] > 0) {
                    const adjacentIndex = cellIndex + 1;
                    if (cellIndexes.indexOf(adjacentIndex) === -1) {
                        adjacentCells.push(adjacentIndex);
                    }
                }
                if (cellIndex + this.maxX < bagArray.length && bagArray[cellIndex + this.maxX] > 0) {
                    const adjacentIndex = cellIndex + this.maxX;
                    if (cellIndexes.indexOf(adjacentIndex) === -1) {
                        adjacentCells.push(adjacentIndex);
                    }
                }
            }

            const validEquips: ItemGameEquip[] = [];
            const validNodes: cc.Node[] = adjacentCells.reduce((acc, cellIndex) => {
                const cellComp = this.cellCompMap.get(cellIndex);
                if (cellComp && cellComp.equipComp) {
                    const shuiguoData = Excel.shuiguo(cellComp.equipComp.equipData.shuiguoId);
                    if (
                        shuiguoData.attackstate !== 5 &&
                        shuiguoData.attackstate !== 8 &&
                        shuiguoData.attackstate !== 9 &&
                        !validEquips.includes(cellComp.equipComp)
                    ) {
                        validEquips.push(cellComp.equipComp);
                        acc.push(cellComp.equipComp.node);
                    }
                }
                return acc;
            }, []);

            if (validNodes.length > 0) {
                isEnd ? this.showBuff(validNodes) : this.showJianTou(validNodes);
            }
        }
    }

    private showBuff(nodes: cc.Node[]): void {
        for (let i = 0; i < nodes.length; i++) {
            const node = nodes[i];
            this.showOneUpBuff(node.convertToWorldSpaceAR(cc.v2(0, 0)));
        }
    }

    private showOneUpBuff(worldPos: cc.Vec2): void {
        let buffNode: cc.Node;
        if (this.upBuffArray.length > 0) {
            buffNode = this.upBuffArray.shift()!;
        } else {
            buffNode = cc.instantiate(this.auto_ui.node_upBuffEffect);
        }

        buffNode.parent = this.auto_ui.node_upBuffFather;
        buffNode.setPosition(buffNode.parent.convertToNodeSpaceAR(worldPos));
        buffNode.active = true;

        buffNode.getChildByName("1")!.getComponent(cc.ParticleSystem)!.resetSystem();
        buffNode.getChildByName("3")!.getComponent(cc.ParticleSystem)!.resetSystem();

        this.scheduleOnce(() => { this.removeOneUpBuff(buffNode); }, 2);
    }

    private removeOneUpBuff(node: cc.Node): void {
        node.removeFromParent();
        node.active = false;
        this.upBuffArray.push(node);
    }

    private showJianTou(nodes: cc.Node[]): void {
        this.hideJianTou();

        nodes.forEach((node, i) => {
            const worldPos = node.convertToWorldSpaceAR(cc.v2(0, 0));
            if (i < this.jianTouArray.length) {
                this.jianTouArray[i].active = true;
                this.jianTouArray[i].setPosition(this.jianTouArray[i].parent!.convertToNodeSpaceAR(worldPos));
            } else {
                const jianTouNode = cc.instantiate(this.auto_ui.node_jiantou);
                jianTouNode.parent = this.auto_ui.node_upBuffFather;
                jianTouNode.active = true;
                jianTouNode.children[0].runAction(cc.repeatForever(cc.sequence(cc.moveTo(0.75, 0, 30), cc.moveTo(0.75, 0, 0))));
                this.jianTouArray.push(jianTouNode);
                jianTouNode.setPosition(jianTouNode.parent!.convertToNodeSpaceAR(worldPos));
            }
        });
    }

    private hideJianTou(): void {
        this.jianTouArray.forEach(node => node.active = false);
    }

    private checkBottomBtnScale(): void {
        // 实现底部按钮缩放的逻辑
    }

    private checkAI(): void {
        if (AICtrl._instance.isOpen) {
            this.scheduleOnce(() => {
                if (this.auto_ui.node_bottomBtn.active) {
                    if (this.getCanDressUpCell()) {
                        if (this.auto_ui.node_bottomBtn.active) {
                            this.setCellFatherMove(true);
                        }
                        this.setTouchStartNode(this.aiPickEquip.node);
                        const targetWorldPos = this.aiPickCell[0].node.convertToWorldSpaceAR(cc.v2(0, 0));
                        const startWorldPos = this.aiPickEquip.getGridNode().children[0].convertToWorldSpaceAR(cc.v2(0, 0));
                        const offset = cc.v2(targetWorldPos.x - startWorldPos.x, targetWorldPos.y - startWorldPos.y);
                        this.aiPickEquip.node.runAction(
                            cc.sequence(
                                cc.moveTo(AICtrl._instance.dragTime, this.aiPickEquip.node.x + offset.x, this.aiPickEquip.node.y + offset.y),
                                cc.callFunc(() => {
                                    this.moveLength = 1000;
                                    this.onChildTouchUp();
                                })
                            )
                        );
                    } else if (this.getUpLevelEquip() || this.getLevelLowSelf()) {
                        this.setTouchStartNode(this.aiPickEquip.node);
                        if (this.aiPickOtherEquip.lockCellArray && this.aiPickOtherEquip.lockCellArray.length > 0) {
                            const targetWorldPos = this.aiPickOtherEquip.node.convertToWorldSpaceAR(cc.v2(0, 0));
                            const startWorldPos = this.aiPickEquip.getGridNode().children[0].convertToWorldSpaceAR(cc.v2(0, 0));
                            const offset = cc.v2(targetWorldPos.x - startWorldPos.x, targetWorldPos.y - startWorldPos.y);
                            this.aiPickEquip.node.runAction(
                                cc.sequence(
                                    cc.moveTo(AICtrl._instance.dragTime, this.aiPickEquip.node.x + offset.x, this.aiPickEquip.node.y + offset.y),
                                    cc.callFunc(() => {
                                        this.moveLength = 1000;
                                        this.onChildTouchUp();
                                    })
                                )
                            );
                        } else {
                            this.scheduleOnce(() => {
                                const targetWorldPos = this.aiPickOtherEquip.node.convertToWorldSpaceAR(cc.v2(0, 0));
                                const startWorldPos = this.aiPickEquip.getGridNode().children[0].convertToWorldSpaceAR(cc.v2(0, 0));
                                const offset = cc.v2(targetWorldPos.x - startWorldPos.x, targetWorldPos.y - startWorldPos.y);
                                this.aiPickEquip.node.runAction(
                                    cc.sequence(
                                        cc.moveTo(AICtrl._instance.dragTime, this.aiPickEquip.node.x + offset.x, this.aiPickEquip.node.y + offset.y),
                                        cc.callFunc(() => {
                                            this.moveLength = 1000;
                                            this.onChildTouchUp();
                                        })
                                    )
                                );
                            });
                        }
                    } else if (this.getEquipCanDressUp()) {
                        this.setTouchStartNode(this.aiPickEquip.node);
                        const targetWorldPos = this.aiPickCell[0].node.convertToWorldSpaceAR(cc.v2(0, 0));
                        const startWorldPos = this.aiPickEquip.getGridNode().children[0].convertToWorldSpaceAR(cc.v2(0, 0));
                        const offset = cc.v2(targetWorldPos.x - startWorldPos.x, targetWorldPos.y - startWorldPos.y);
                        this.aiPickEquip.node.runAction(
                            cc.sequence(
                                cc.moveTo(AICtrl._instance.dragTime, this.aiPickEquip.node.x + offset.x, this.aiPickEquip.node.y + offset.y),
                                cc.callFunc(() => {
                                    this.moveLength = 1000;
                                    this.onChildTouchUp();
                                })
                            )
                        );
                    } else if (this.getCanResetEquipPool()) {
                        AICtrl._instance.displayClickButton(this.auto_ui.btn_ResetBtn.node, () => {
                            this.sliderResetClick();
                            this.checkAI();
                        });
                    } else if (this.getCanVideoResetEquipPool()) {
                        AICtrl._instance.displayClickButton(this.auto_ui.btn_VideoResetBtn.node, () => {
                            this.resetEquip(false, true, false);
                            this.auto_ui.btn_VideoResetBtn.node.active = false;
                            this.checkAI();
                        });
                    } else if (this.checkIsBigLevel()) {
                        AICtrl._instance.displayClickButton(this.auto_ui.btn_ResetBtn.node, () => {
                            this.sliderResetClick();
                        });
                    } else {
                        AICtrl._instance.displayClickButton(this.auto_ui.btn_start.node, () => {
                            this.gameStart();
                        });
                    }
                } else {
                    AICtrl._instance.displayClickButton(this.auto_ui.btn_UseGeZiBtn.node, () => {
                        this.setCellFatherMove(false);
                        this.checkAI();
                    });
                }
            }, AICtrl._instance.aiCDTime);
        }
    }


    private getCanDressUpCell(): boolean {
        this.aiPickEquip = null;
        this.aiPickCell = null;

        let hasGeZi = false;
        this.equipPool.forEach((equipComp) => {
            if (equipComp.isGeZiType) {
                hasGeZi = true;
            }
        });

        if (!hasGeZi) {
            return false;
        }

        let geZiEquip: ItemGameEquip | null = null;
        this.equipPool.forEach((equipComp) => {
            if (equipComp.isGeZiType && !geZiEquip) {
                geZiEquip = equipComp;
            }
        });

        if (geZiEquip) {
            const geZiOffsets = geZiEquip.getGridNode().children.map((child, i, arr) => {
                return i === 0 ? cc.v2(0, 0) : cc.v2(child.x - arr[0].x, child.y - arr[0].y);
            });

            for (const baseCell of this.baseCellCompArray) {
                const targetPositions = geZiOffsets.map((offset) => cc.v2(baseCell.node.x + offset.x, baseCell.node.y + offset.y));
                const validCells = targetPositions
                    .map((targetPos) =>
                        this.baseCellCompArray.find(
                            (cell) => cc.Vec2.distance(targetPos, cell.node.getPosition()) < 10 && GameDataMgr.getGameBag.bagArray[cell.cellData.cellIndex] === -1
                        )
                    )
                    .filter((cell) => cell !== undefined) as ItemGameBagCell[];

                if (validCells.length === targetPositions.length && this.checkOneCellArrayIsOk(validCells.map((cell) => cell.cellData.cellIndex), GameDataMgr.getGameBag.bagArray)) {
                    this.aiPickEquip = geZiEquip;
                    this.aiPickCell = validCells;
                    return true;
                }
            }
        }

        return false;
    }

    private getUpLevelEquip(): boolean {
        this.aiPickEquip = null;
        this.aiPickOtherEquip = null;

        const poolEquips = Array.from(this.equipPool.values());
        const dressUpEquips = Array.from(this.dressUpEquipMap.values());

        const findMatchingEquip = (equipArray1: ItemGameEquip[], equipArray2: ItemGameEquip[]): [ItemGameEquip, ItemGameEquip] | null => {
            for (const equip1 of equipArray1) {
                for (const equip2 of equipArray2) {
                    if (
                        equip1 !== equip2 &&
                        equip1.equipData.equipLevel === equip2.equipData.equipLevel &&
                        (equip1.equipData.shuiguoId === equip2.equipData.shuiguoId ||
                            (equip1.equipData.equipLevel === GameGlobalVariable.normalMaxLevel - 1 &&
                                LogicGetEquip.getInstance.getZaZhongId(equip1.equipData.shuiguoId) === equip2.equipData.shuiguoId))
                    ) {
                        return [equip1, equip2];
                    }
                }
            }
            return null;
        };

        let matchingEquip = findMatchingEquip(poolEquips, poolEquips);
        if (!matchingEquip) {
            matchingEquip = findMatchingEquip(poolEquips, dressUpEquips);
        }
        if (!matchingEquip) {
            matchingEquip = findMatchingEquip(dressUpEquips, dressUpEquips);
        }

        if (matchingEquip) {
            [this.aiPickEquip, this.aiPickOtherEquip] = matchingEquip;
            return true;
        }

        return false;
    }

    private getLevelLowSelf(): boolean {
        this.aiPickEquip = null;
        this.aiPickOtherEquip = null;

        const poolEquips = Array.from(this.equipPool.values());
        const dressUpEquips = Array.from(this.dressUpEquipMap.values());

        const matchingEquip = poolEquips.find((equip) =>
            dressUpEquips.some(
                (dressEquip) =>
                    dressEquip.equipData.shuiguoId === equip.equipData.shuiguoId &&
                    dressEquip.equipData.equipLevel < equip.equipData.equipLevel
            )
        );

        if (matchingEquip) {
            this.aiPickEquip = matchingEquip;
            this.aiPickOtherEquip = dressUpEquips.find(
                (dressEquip) =>
                    dressEquip.equipData.shuiguoId === matchingEquip.equipData.shuiguoId &&
                    dressEquip.equipData.equipLevel < matchingEquip.equipData.equipLevel
            )!;
            return true;
        }

        return false;
    }

    private getEquipCanDressUp(): boolean {
        this.aiPickEquip = null;
        this.aiPickCell = null;

        const sortedEquipArray = Array.from(this.equipPool.values()).sort(
            (a, b) => b.equipData.equipLevel - a.equipData.equipLevel
        );

        for (const targetEquip of sortedEquipArray) {
            const geZiOffsets = targetEquip
                .getGridNode()
                .children.map((child, i, arr) =>
                    i === 0 ? cc.v2(0, 0) : cc.v2(child.x - arr[0].x, child.y - arr[0].y)
                );

            for (const baseCell of this.auto_ui.node_cubeFather.children) {
                const targetPositions = geZiOffsets.map((offset) =>
                    cc.v2(baseCell.x + offset.x, baseCell.y + offset.y)
                );
                const validCells = targetPositions
                    .map((targetPos) =>
                        Array.from(this.cellCompMap.values()).find(
                            (cell) =>
                                cc.Vec2.distance(targetPos, cell.node.getPosition()) < 10 &&
                                GameDataMgr.getGameBag.bagArray[cell.cellData.cellIndex] === 0
                        )
                    )
                    .filter((cell) => cell !== undefined) as ItemGameBagCell[];

                if (validCells.length === targetPositions.length) {
                    this.aiPickEquip = targetEquip;
                    this.aiPickCell = validCells;
                    return true;
                }
            }
        }

        return false;
    }

    private getCanResetEquipPool(): boolean {
        return GameDataMgr.getGameBag.silverCoin >= this.oneBuyMoney;
    }

    private getCanVideoResetEquipPool(): boolean {
        return this.auto_ui.btn_VideoResetBtn.node.active;
    }

    private checkIsBigLevel(): boolean {
        if (GameGlobalVariable.nowlevel) {
            const maxBoshu = Excel.shuiguoguanqia(GameGlobalVariable.nowlevel)
                .levelboshuid.length;
            const currentBoshu = GameDataMgr.getCurrentLevelWaveState(GameGlobalVariable.nowlevel, 2) + 1;
            LogMgr.debug("maxBoShu:", maxBoshu, "boshu:", currentBoshu);

            let resetCount = 0;
            if (maxBoshu <= 10) {
                if (currentBoshu === 4) resetCount = 5;
                else if (currentBoshu === 7) resetCount = 10;
                else if (currentBoshu === 10) resetCount = 20;
            } else if (maxBoshu <= 15) {
                if (currentBoshu === 5) resetCount = 5;
                else if (currentBoshu === 10) resetCount = 10;
                else if (currentBoshu === 15) resetCount = 20;
            } else {
                if (currentBoshu === 5) resetCount = 5;
                else if (currentBoshu === 10) resetCount = 10;
                else if (currentBoshu === 20) resetCount = 20;
            }

            if (resetCount !== 0) {
                if (this.mustResetTime === -1) {
                    this.mustResetTime = 0;
                    return true;
                }
                if (this.mustResetTime >= resetCount) {
                    this.mustResetTime = -1;
                    return false;
                }
            }
        }
        return false;
    }
}

